3

I want to run linear regression for the same outcome and a number of covariates minus one covariate in each model. I have looked at the example on this page but could that did not provide what I wanted.

Sample data

a <- data.frame(y = c(30,12,18), x1 = c(7,6,9),  x2 = c(6,8,5),
                x3 = c(4,-2,-3), x4 = c(8,3,-3), x5 = c(4,-4,-2))
m1 <- lm(y ~ x1 + x4 + x5, data = a)    
m2 <- lm(y ~ x2 + x4 + x5, data = a)   
m3 <- lm(y ~ x3 + x4 + x5, data = a)

How could I run these models in a short way and and without repeating the same covariates again and again?

zx8754
  • 52,746
  • 12
  • 114
  • 209
WangoR
  • 361
  • 2
  • 5
  • 10

1 Answers1

2

Following this example you could do this:

lapply(1:3, function(i){
    lm(as.formula(sprintf("y ~ x%i + x4 + x5", i)), a)
})
Community
  • 1
  • 1
Backlin
  • 14,612
  • 2
  • 49
  • 81
  • Thanks Backlin for your answer. I think I have not expressed my question clearly. In the models x4 and x5 are present in all models, but x1, x2 and x3 are exchangeable and are present only in one model separately. – WangoR May 07 '15 at 11:27
  • Aha, no problem I'll update the answer. I was fooled by the extra `+` between `x1` and `x4` so I thought you wanted all in between too. – Backlin May 07 '15 at 11:29