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.

Revisions

  1. Chris Brown revised this gist Mar 25, 2024. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion rw2sim.R
    Original file line number Diff line number Diff line change
    @@ -8,12 +8,13 @@
    # needs to be two consecutive points, given we are working with
    # second order differences.

    rw2sim <- function(n, sd, x0){
    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
  2. Chris Brown created this gist Mar 25, 2024.
    24 changes: 24 additions & 0 deletions rw2sim.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    #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){
    #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
    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
    }