0

In order to use the for loop, I'm trying to replace the arguments in this function by variables:

lm(mpg~cylinders, data=Auto)

So I did this:

var1='cylinders'

lm((paste('mpg ~',var1)), data = Auto)

It worked fine.

Now, I wonder how we can replace the arguments cylinders+acceleration by var1 and var2.

So tried the same method. I tried to replace this:

lm(mpg~cylinders+acceleration, data=Auto)

by

var1='cylinders'
var2 = 'acceleration'

lm((paste('mpg ~',var1+var2)), data = Auto)

But I got a message error:

Error in var1 + var2 : non-numeric argument to binary operator

So I want to learn how I can work with var1 and var2 in order to use for loop afterwards.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
user75086
  • 101
  • 1
  • 2
  • 2
    Do: `(paste('mpg ~',var1,"+",var2))`. Unlike python, you cannot use `+` to directly concat strings, as far as I know. – NelsonGon Jun 14 '20 at 15:52
  • 1
    Does this answer your question? [How to use reference variables by character string in a formula?](https://stackoverflow.com/questions/17024685/how-to-use-reference-variables-by-character-string-in-a-formula) – NelsonGon Jun 14 '20 at 15:54
  • 1
    @NelsonGon It worked thank you. The answer of this other question is more general and it will be very helpful. Thanks again – user75086 Jun 14 '20 at 16:35
  • Please follow the instructions at the top of the [tag:r] tag page when posting. In particular Auto is not part of base R and no library statements were used so the code is not reproducible. – G. Grothendieck Jun 14 '20 at 17:22

1 Answers1

1

Use reformulate to generate the formula.

var1 <- 'cyl'
var2 <- 'disp'
fo <- reformulate(c(var1, var2), "mpg")
lm(fo, mtcars)

or you could write it like this which gives the same answer except the above shows literally fo in the Call: line in the output whereas the code below expands fo in the Call: line in the output.

do.call("lm", list(fo, quote(mtcars)))

giving:

Call:
lm(formula = mpg ~ cyl + disp, data = mtcars)

Coefficients:
(Intercept)          cyl         disp  
   34.66099     -1.58728     -0.02058  
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341