rarimasapply

R Sapply function seems to produce slightly different values to for loop approach


I have written two blocks of R-code. I believe that they should both do exactly the same thing - except that one uses a for-loop approach and one uses the sapply function. However, they produce slightly different results. Does anyone know what is causing the slight differences here? Interestingly, both methods produce the same value for the first elements of the output vectors.

Method1:

set.seed(967)
n <- replicate(1000, 200)
ACF2MA <- sapply(n, function(n1) {
  acf(arima.sim(n1, model=list(ma=c(0.4))), plot=FALSE)$acf[3]
})
ACF2AR <- sapply(n, function(n1) {
  acf(arima.sim(n1, model=list(ar=c(0.45))), plot=FALSE)$acf[3]
})

Method2:

ACF2AR1 <- 1:1000 

for (i in 1:1000) { 
  YMA <- arima.sim(n=200, model=list(ma=c(0.4))) 
  YAR <- arima.sim(n=200, model=list(ar=c(0.45))) 
  ACF2MA1[i] <- acf(YMA, plot=FALSE)$acf[3] 
  ACF2AR1[i] <- acf(YAR, plot=FALSE)$acf[3] 
}

Many thanks in advance!

I was expecting the exact same results.


Solution

  • The difference is that you're running the simulations in a different order. In stochastic (pseudo-random) simulations, that matters. In the sapply case you run 1000 MA sims and then 1000 AR sims; in the loop you alternate MA and AR sims.