What is the best way to run a loop of regressions in R?

Posted by stevejb on Stack Overflow See other posts from Stack Overflow or by stevejb
Published on 2010-04-17T00:22:21Z Indexed on 2010/04/17 0:43 UTC
Read the original article Hit count: 341

Filed under:
|

Assume that I have sources of data X and Y that are indexable, say matrices. And I want to run a set of independent regressions and store the result. My initial approach would be

results = matrix(nrow=nrow(X), ncol=(2))
for(i in 1:ncol(X)) {
        matrix[i,] = coefficients(lm(Y[i,] ~ X[i,])

}

But, loops are bad, so I could do it with lapply as

out <- lapply(1:nrow(X), function(i) { coefficients(lm(Y[i,] ~ X[i,])) } )

Is there a better way to do this?

© Stack Overflow or respective owner

Related posts about rstats

Related posts about r