Hi,

I guess my question is really more about the nested for loop construct and
whether it is doing what I intend it to do in my code in the previous post.
I would be grateful if anyone who has used nested loops could let me know if
I am doing something wrong.

Thanks,

rcoder



rcoder wrote:
> 
> Hi everyone,
> 
> I'm experiencing difficulty getting the results I want when I use a nested
> for loop. I have a data set to which I perform some calculations, and then
> try to apply a regression over a rolling window. The code runs, but the
> regression results I am getting (intercept and slope) are simply the same,
> repeated again and again in the results matrix. The regression does not
> seem to be obeying the instructions of the nested loop, which intend it to
> calculate regression coefficients over a data one row at a time. I have
> been struggling with the code for many days now, testing various parts,
> and I cannot seem to get the nested loop to work as I want it to. I would
> be very grateful for any suggestions. Below is a brief version of my code:
> 
> #Code start
> library(zoo)
> seed.set(1)
> Pmat<-matrix(rnorm(1000), nrow=100, ncol=100)
> maxcol<-ncol(Pmat)
> maxrow<-nrow(Pmat)
> startrow<-10                  
> period<-10            
> wind<-2                               #roll window
> subdiv<-period/wind
> rollstart<-11                                 #start roll at period+1
> #converting Pmat into ts for rollapply() to work...    
> PmatTS<-ts(Pmat)
> Preg<-matrix(NA,ncol=maxcol,nrow=2*maxrow)
> PmatWt<-matrix(NA, nrow=subdiv,ncol=maxcol)
> mult_col<-matrix(1:5, nrow=5, ncol=1)
> #rolling calculations...
> for (i in (rollstart):maxrow)           
>       {
> #extract the relevant timeframe...
> dslice<-PmatTS[(i-period):i,]         
> dslicets<-ts(dslice)
> #operating on sliced data...
> Pmin<-rollapply(dslicets, wind, by=wind, min, na.rm=F)          
> Pmax<-rollapply(dslicets, wind, by=wind, max, na.rm=F)     
> Pmult<-Pmin*Pmax                        #calculating product
> tt<-time(Pmult)
> for (j in 1:5)                                #1st nested loop
>       {
> PmatWt[j,]<-Pmult[j,]*mult_col[j,]
>       }
> #rolling regression analysis...
> for (k in 1:maxcol)                   #2nd nested loop
>             {
>       sel_col<-PmatWt[,k] 
>       if(!all(is.na(sel_col))) {Preg[,k]<-coef(lm(tt~sel_col))}
>             }
>       }
> #Code End
> 
> Thanks,
> 
> rcoder
> 

-- 
View this message in context: 
http://www.nabble.com/problem-with-nested-loop-for-regression-tp18792841p18815273.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to