Skip to content

Instantly share code, notes, and snippets.

@cbrown5
Last active March 25, 2024 20:43
Show Gist options
  • Save cbrown5/008c75e516d9adb8bc9854ca92f7dec3 to your computer and use it in GitHub Desktop.
Save cbrown5/008c75e516d9adb8bc9854ca92f7dec3 to your computer and use it in GitHub Desktop.
Simulate from a random walk order 2 model
#Simulate from an RW2 (random walk order 2) model.
# Useful for generating predictions from INLA RW2 models.
# When forecast, RW2 models predict continuation of trend, with
# deviations from the trend controlled by the sd parameter.
#
# See: https://inla.r-inla-download.org/r-inla.org/doc/latent/rw2.pdf
# Can intialize the RW2 at a given starting point, this needs
# needs to be two consecutive points, given we are working with
# second order differences.
rw2sim <- function(n, sd, x0, seed=28937){
#n: number of time steps
#sd: sd of the RW2 process
#X0: starting points, should be length 1 or 2
# if length 1 then assumes first two starting points
# are the same
set.seed(seed)
z <- rnorm(n, sd = sd)
x <- numeric(n)
x[1:2] <- x0
for (i in 3:n){
x[i] = z[i] - x[i-2] + 2*x[i-1]
}
x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment