for
loop:
N <- 500;
ro <- 0.6; a <- 1
set.seed(1)
v <- ts(rnorm(N,0,1))
# [1] -0.626453811 0.183643324 -0.835628612 1.595280802 0.329507772
# [496] -1.108909998 0.307566624 -1.106894472 0.347653649 -0.873264535
y <- ts(rep(0,N)) # y[1]:=0 defined
for (t in 2:500){ y[t] <- a + ro*y[t-1] + v[t] }
y
# [1] 0.00000000 [2] 1.18364332
# [3] 0.87455738=1+0.6*1.18364332+(-0.835628612)
# [4] 3.12001523=1+0.6*0.87455738+(1.595280802)
# [499] 2.55513301 1.65981527
mean(y) #2.549763
I wanted to convert the above for
loop to an apply-family version:
N <- 500; ro <- 0.6; a <- 1
set.seed(1)
v <- as.data.frame(rnorm(N,0,1))
# 1: -0.626453811 2: 0.183643324 3: -0.835628612 4: 1.595280802 5: 0.329507772
# 496: -1.108909998 497: 0.307566624 498: -1.106894472 499: 0.347653649 500:-0.873264535
y <- as.data.frame(c(y1=0,rep(0,N-1))) # index starts at 1. y[1]:=0 defined
y <- c(y[1,], unlist(apply(as.matrix(2:500), 1, function(t) { y[t,] <- a + ro*y[t-1,] + v[t,] })))
y
# [1] 0.000000000 [2] 1.183643324
# [3] 0.164371388=1+0.6*0+(-0.8356286124)
# [4] 2.595280802=1+0.6*0+(1.5952808025)
# [496] -0.108909998 1.307566624 -0.106894472 1.347653649 0.126735465
mean(y) # 1.021897
The above code does not give the results in for
loop. I discovered what is wrong: in apply
, in the iteration equation, previous values of y
are not used; instead, y <- as.data.frame(c(y1=0,rep(0,N-1)))
; i.e. yt=0
is used for all t
.
What to do to make successful apply-family?