r - for loop only stores last value -
i wrote loop in r , try store computed values in matrix. unfortunately, saves last value. browsed internet , found out, problem can solved indexing. however, , still doesn't work. see mistake?
data set:
require(stats) data <- ts.union(a=arima.sim(model=list(ar=c(.9,-.2)), n=144), b=arima.sim(model=list(ar=c(.6, -.3)), n=144), c=arima.sim(model=list(ar=c(-.2,-.6)), n=144), d=arima.sim(model=list(ar=c(-.1,-.6)), n=144), e=arima.sim(model=list(ar=c(.2,-.6)), n=144), f=arima.sim(model=list(ar=c(.2,.7)), n=144), g=arima.sim(model=list(ar=c(.3,.2)), n=144), h=arima.sim(model=list(ar=c(-.4,.3)), n=144), i=arima.sim(model=list(ar=c(.1,-.7)), n=144), j=arima.sim(model=list(ar=c(.8,.1)), n=144)) data <- ts(data, start=c(2007, 2), frequency=12) loop:
require(vars) for(i in 1:12){ # compute factors, window 5.5 years wide factors <- ts(prcomp(window(data, start=c(2007, (i+1)), end=c(2012, i+6)), center=t, scale=t)$x[,1:5], start=c(2007,(i+1)), frequency=12) # estimate var model model <- var(window(data, start=c(2007, (i+1)), end=c(2012, i+6)), exogen=factors, type="const") # forecast factors factor.fcst <- sapply(factors, function(x) predict(auto.arima(x, stationary=t, seasonal=f), n.ahead=12))[1,] factor.fcst <- cbind(factor.fcst$pc1, factor.fcst$pc2, factor.fcst$pc3, factor.fcst$pc4, factor.fcst$pc5) colnames(factor.fcst) <- colnames(factors) # forecast model a_fcst <- ts(predict(model, dumvar=factor.fcst, n.ahead=12, ci=0.95)$fcst$a[,1], start=c(2012, (i+7)), frequency=12) # compute rmse rmse <- matrix(ncol=1, nrow=12) rmse[i,] <- sqrt(mean((window(data[,1], start=c(2012, (i+7)), end=c(2012, (i+18))) - a_fcst)^2)) print(rmse) } thanks help!
here's simpler example:
d1 <- seq(10) ans1 <- vector(length=length(d1), mode="double") (i in seq.int(length(d1))){ ans1[i] <- sqrt(d1[i]) } now, if take second line , put inside loop, last value returned i.e. value of ans1 reset each time loop run.
this sort of code far 'best practice'. said, loops can useful first step towards vectorizing function, can easier read , (rarely) can faster.
Comments
Post a Comment