Hi, is there a function that replaces the following code? n=200 boot.x[1]=odhad+boot.res[1] #(boot.x[0]=1) for (j in 1:(n-1)) { boot.x[j+1]=odhad*boot.x[j]+boot.res[j+1] } This is nested in two other loops, and I am looking for some way to improve code performance I tried sapply and cumprod but no success. Thanks Jan -- View this message in context: http://r.789695.n4.nabble.com/Replacing-the-for-loop-for-time-series-buid-up-tp3094421p3094421.html Sent from the R help mailing list archive at Nabble.com.
On Dec 19, 2010, at 8:08 AM, Torch wrote:> > Hi, > is there a function that replaces the following code? > > n=200 > boot.x[1]=odhad+boot.res[1] #(boot.x[0]=1)No. there is no boot.x[0] ... in R anyway.> > for (j in 1:(n-1)) { > boot.x[j+1]=odhad*boot.x[j]+boot.res[j+1] > } > > This is nested in two other loops, and I am looking for some way to > improve > code performance > I tried sapply and cumprod but no success.Probably because you didn't use paper and pencil to figure out what x_n was going to be. You end up with a series that looks like: boot.x[n] = odhad^n + boot.res[1]*odhad^(n-1) +boot.res[2]*odhad^(n-2) + ... boot.res[n] I'm thinking you should play around with n=20 instead of 200 because I don't know what odhad might be and I'd be afraid of overflow with the ^200 operation. Here's a failed attempt: geo_od <- odhad^(19:0) geo_res <- boot.res*geo_od boot.x <- odhad^(1:20) + cumsum(geo_res) But that's not correct ... except for the fact that it does get the last term correct.> > Thanks > Jan > -- > View this message in context: http://r.789695.n4.nabble.com/Replacing-the-for-loop-for-time-series-buid-up-tp3094421p3094421.html > Sent from the R help mailing list archive at Nabble.com.David Winsemius, MD West Hartford, CT
Torch wrote:> > Hi, > is there a function that replaces the following code? > > n=200 > boot.x[1]=odhad+boot.res[1] #(boot.x[0]=1) > > for (j in 1:(n-1)) { > boot.x[j+1]=odhad*boot.x[j]+boot.res[j+1] > } > > This is nested in two other loops, and I am looking for some way to > improve code performance > I tried sapply and cumprod but no success. >You can have a look at filter. Test example: alpha <- 0.75 N <- 10 boot.res <- ts(rnorm(N)) boot.res val.init <- boot.res[1] + alpha boot.x <- ts(val.init, start=1,end=N) for(t in 2:N) { boot.x[t] <- alpha*boot.x[t-1] + boot.res[t] } boot.x boot.x.filter <- ts(c(val.init,filter(boot.res[-1],filter=alpha,method="recursive",init=val.init))) boot.x.filter boot.x - boot.x.filter succes Berend -- View this message in context: http://r.789695.n4.nabble.com/Replacing-the-for-loop-for-time-series-buid-up-tp3094421p3094757.html Sent from the R help mailing list archive at Nabble.com.