[R] Saving estimates after nested loops

D.Soudis
Fri, 08 Jun 2012 09:50:01 -0000

Hi R-listers,

Savings regression results after a loop is straightforward. But what about when
you have nested loops?
I am running a regression of the form

lm(y~1+x+M+ D[,i] + D[,j] + D[,k])

where x is the variable of interest. M and D are vectors with other covariates.
Vectors "M" and "x" are included in every regression. Then i
loop over the columns of D to use all unique combinations of
covariates in that matrix and save the results for variable "x" in
each run. This is the code :
(due to the random numbers it will produce 10 similar betas,t.values etc...)

M<-matrix(rnorm(100),100,3)
D<-matrix(rnorm(100),100,5)
y<-matrix(rnorm(100),100,1)
x<-matrix(rnorm(100),100,1)
beta<-NULL
t.value<-NULL
sd<-NULL
i<-1
while(i<=ncol(D)){
  j<-i+1
  while(j<=ncol(D)){
    k<-j+1
    while(k<=ncol(D)){
      Res<-lm(y~1+x+M+ D[,i] + D[,j] + D[,k])
      beta<-cbind(summary(Res)$coef[2])
      t.value<-cbind(summary(Res)$coef[2,3])
      sd<-cbind(summary(Res)$coef[2,2])
      k<-k+1
    }
    j<-j+1
  }
  i<-i+1
}

If i looped over only, say k, then something like:

beta[k]<-cbind(summary(Res)$coef[2])


would have been sufficient...but what now that there are loops over i,j,k?
Maybe "while" is a bad idea??

I would appreciate your answers!

Best Regards,
Dimitrios Soudis
Ph.D. Candidate
Faculty of Economics
U. of Groningen

	[[alternative HTML version deleted]]