[R] Saving estimates after nested loops

Rui Barradas ruipbarradas at sapo.pt
Fri Jun 8 15:43:04 CEST 2012


Hello,

Your cbind() are wrong, they are NOT binding columns, just column.
The problem would be solved with

beta <- cbind(beta, summary(Res)$coef[, 1])

and the same for 't.value' and 'sd'.
By the way, 'sd' is a bad name for a variable, it's already an R function.

A better way of solving the problem is using combn().
See the output of

cmb <- combn(5, 3)  # matrix D has 5 cols, taken 3 at a time

Then,

nr <- NCOL(1) + NCOL(x) + NCOL(M) + NCOL(D[, cmb[, 1]])
nc <- NCOL(cmb)

beta <- t.value <- sdev <- matrix(nrow=nr, ncol=nc)
for(i in 1:nc){
	Dcols <- cmb[, i]
	Res <- lm(y ~ 1 + x + M + D[, Dcols])
	summRes <- summary(Res)$coef
	beta[, i] <- summRes[, 1]
	sdev[, i] <- summRes[, 2]
	t.value[, i] <- summRes[, 3]
}


Hope this helps,

Rui Barradas

Em 08-06-2012 10:50, D.Soudis escreveu:
>   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]]
>
>
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list