[R] Other ways to lm() regression? (non-loop?)

iliketurtles isaacm200 at gmail.com
Mon Dec 26 13:29:30 CET 2011


Hi, I'm quite new to R (1 month full time use so far). I have to run loop
regressions VERY often in my work, so I would appreciate some new
methodology that I'm not considering. 

#---------------------------------------------------------------------------------------------
y<-matrix(rnorm(100),ncol=10,nrow=10)
x<-matrix(rnorm(50),ncol=5,nrow=10)

#Suppose I want to run the specification y=A+Bx+error, for each and every
y[,n] onto each and every x[,n].
#So with:
ncol(y);ncol(x)
#I should end up with 10*5=50 regressions in total.

#I know how to do this fine:
MISC1<-0
for(i in 1:ncol(y)){
for(j in 1:ncol(x)){
reg<-lm(y[,i]~x[,j])
MISC1<-cbind(MISC1,coef(reg)) #for coefficients
}}
coef<-matrix(MISC1[,-1],ncol=50)

coef[,1];coef(lm(y[,1]~x[,1])) #test passed
ncol(coef)                                #as desired, 50 regressions.
#---------------------------------------------------------------------------------------------

Now for my question: Is there easier or better methods of doing this? I know
of a lapply method, but the only lapply way I know of for lm(..) is
basically doing a lapply inside of a lapply, meaning it's exactly the same
as the double loop above... I'm looking to escape from loops. 

Also, if any of you could share your top R tips that you've learned over the
years, I'd really appreciate it. Tiny things like learning that array() and
matrix() can have a 3rd dimension, learning of strsplit, etc.. have helped
me immeasurably. (Not that I'm also googling for this stuff! I'm doing R 14
hours a day!).

Thanks. 

--
View this message in context: http://r.789695.n4.nabble.com/Other-ways-to-lm-regression-non-loop-tp4234487p4234487.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list