Search code examples
rtime-seriessimulationautocorrelation

Time series simulation (multiple observations)


I am trying to simulate some time series data with multiple observations. I do want to set up autocorrelations for each individual within their own time period (r=.7). The time periods are of different size:size <- c(10, 50, 100, 200, 300, 400, 440, 500). For example, first individual has 10 time points, second individual has 50 time points, etc. In the end, I want to return a data frame that includes id, a and b. Here is what I have tried but to no avail. I am pretty new to R and so I appreciate any help.

size <- c(10, 50, 100, 200, 300, 400, 440, 500)
results <- sapply(size, function(x)
                  a=rnorm(size),
                  ar.epsilon <- arima.sim(list(order = c(1,0,0), ar = 0.7), n = size, sd=20),
                  b = 50 + 25*a + ar.epsilon,
                  data.frame(id, a, b))

Solution

  • Does this come close to what you intend to do? I'm not sure what id stands for.

    size <- c(10, 50, 100, 200, 300, 400, 440, 500)
    set.seed(420)
    results_a <- matrix(NA, nrow = max(size), ncol = length(size))
    results_b <- matrix(NA, nrow = max(size), ncol = length(size))
    for(i in 1:ncol(results)){
      a <- rnorm(size[i])
      ar.epsilon <- arima.sim(list(order = c(1,0,0), ar = 0.7), n = size[i], sd=20)
      b = size[i]*a + ar.epsilon
      results_id[]
      results_a[c(1:size[i]), i] <- a
      results_b[c(1:size[i]), i] <- b
    }
    
    colnames(results_a) <- paste0('id.a.', size)
    colnames(results_b) <- paste0('id.b.', size)
    
    result_final <- data.frame(results_a, results_b)
    result_final <- result_final[, c(1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15, 8, 16)]
    head(result_final, 5)
         id.a.10    id.b.10    id.a.50    id.b.50    id.a.100  id.b.100   id.a.200  id.b.200   id.a.300   id.b.300
    1  0.2677109   4.135141 -1.2479756 -117.59951  0.98359034  62.78846 -0.4334481 -80.73017 -1.2820512 -376.21611
    2 -0.9367075 -31.289128 -2.8949090 -177.02084 -0.09517645 -24.60170 -0.2134596 -24.28731 -0.2437892 -105.31801
    3  0.5962061  -2.716978  1.1995795   68.50393 -1.13753051 -91.86198  1.2898376 291.26922  0.5395736  118.88174
    4 -0.3120436 -22.395355  0.2200063   55.90104 -0.23305847 -32.09204  0.7150280 168.96521 -0.1842391  -63.82123
    5  0.3979791 -33.284591  0.9722208  102.26825 -0.45663605 -58.60094  0.4104681  70.51101  1.2605879  373.00674
         id.a.400    id.b.400  id.a.440  id.b.440   id.a.500  id.b.500
    1 -0.81734653 -354.499825  1.416543  649.6649 -0.7634678 -399.9059
    2  1.77813114  670.127238  0.301712  149.6443  0.4791241  210.1626
    3 -1.13121629 -501.422591  2.129244  950.8821  1.4002161  710.6371
    4  0.08281154   -2.199712  1.321002  610.5567  0.2423353  140.2799
    5  0.68390623  262.957092 -1.161112 -497.6224 -0.3141071 -179.2746