-1

I'm trying to regress each column of a matrix (dependent variable) against a single column vector (independent variable), and store the coefficients and residuals. Here's a sample data and my code so far:

gwthRatesAllCities06To08 <- matrix(1:60, nrow = 4, ncol = 15)
natGwthRates06To08 <- c(2,1,3,5)

for (i in 1 : ncol(gwthRatesAllCities06To08)) {
OLSEst[[i]]<- lm(formula = gwthRatesAllCities06To08[,i] ~ natGwthRates06To08)
}

However, the code above does not give me what I want, could you please help me figure out the reason? Many thanks in advance!

Vera Lee
  • 29
  • 4
  • 1
    Check out `fit <- lm(gwthRatesAllCities06To08 ~ natGwthRates06To08); coef(fit); residuals(fit)`. – Roland Oct 24 '18 at 14:50

3 Answers3

2

lm can regress multiple Y vectors on the same right hand side. Just specify the left hand side to be a matrix whose columns are the Y vectors.

y <- matrix(1:60, nrow = 4, ncol = 15)
x <- c(2,1,3,5)

fm <- lm(y ~ x)

coef(fm) # the 15 columns of coef are the 15 sets of coefficients
resid(fm) # the 15 columns of resid are the 15 sets of residuals
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

I think your code works well, I can retrieve the coefficients and residuals:

OLSEst <- list()
for (i in 1 : ncol(gwthRatesAllCities06To08)) {
  OLSEst[[i]]<- lm(formula = gwthRatesAllCities06To08[,i] ~ natGwthRates06To08)
}
mod <- OLSEst[[15]]
> mod$coefficients
       (Intercept) natGwthRates06To08 
        56.7714286          0.6285714 
> mod$residuals
          1           2           3           4 
-1.02857143  0.60000000  0.34285714  0.08571429 
gaut
  • 5,771
  • 1
  • 14
  • 45
  • 1
    You're right thanks! I just tried out as well and the code works. It's just if I `View(OLSEst)`, the 1st element on the list shows different coefficients than if I use `OLSEst[[1]]` to retrieve the 1st element. Do you know what might be the reason? – Vera Lee Oct 24 '18 at 14:58
1

You need to create the list first, outside of the for-loop. Then, add to the list with your results.

gwthRatesAllCities06To08 <- matrix(1:60, nrow = 4, ncol = 15)
natGwthRates06To08 <- c(2,1,3,5)
OLSEst <- list()

for (i in 1 : ncol(gwthRatesAllCities06To08)) {
  OLSEst[[i]]<- lm(formula = gwthRatesAllCities06To08[,i] ~ natGwthRates06To08)
}

If you just want coefficients, consider just taking the parts of the regression objects you want. Check below to get started.

test <- lm(formula = gwthRatesAllCities06To08[,i] ~ natGwthRates06To08)
test$coefficients
Breaker
  • 105
  • 1
  • 9