Skip to content
Prev 163512 / 398506 Next

Variables inside a for

Hi Raphael,

If you truly only need to run 4 regressions you might be less confused 
if you just do

test1 <- lm(TX01 ~ INCOME, data = database)
test2 <- lm(TX02 ~ INCOME, data = database)
test3 <- lm(TX03 ~ INCOME, data = database)
test4 <- lm(TX04 ~ INCOME, data = database)

If you need to do this 100 times it is not very practical. Here I'm 
going to assume that your data are in a data frame with the first 100 
columns being dependent variables and column 101 being the independent 
variable. Your first option is to select the component from the lm 
object you are interested in, let's assume the coefficients. Then

n <- 100
mat <- matrix(nrow=n,ncol=2)
for(i in 1:n){
mat[i,] <- lm(data[,i] ~ data[,101])$coef
}

The resulting matrix mat will hold the coefficients of the 100 
regressions. Again, if you really need the whole lm object then you 
could do the following

n <- 100
arr <- array(list(),c(1,n))
for(i in 1:n){
arr[[i]] <- lm(data[,i] ~ data[,101])
}

The resulting array will have the 100 lm objects, which you can then 
examine.

Hope this helps,

Fernando
Raphael Saldanha wrote: