Roy
Roy

Reputation: 603

What does "/" mean in R when writing a regression formula in lm()

The formula is just like this. I don't quite understand the usage of the notion "/". It seems that "/" usually be used in dummy variables. But I am not sure about its usage.

lm(y~x/z,data = data.frame(x = rnorm(6), y = rnorm(6), z = rep(0:1,each=3)))

Upvotes: 22

Views: 2409

Answers (1)

Lennyy
Lennyy

Reputation: 6132

lm(y ~ x/z, data) is just a shortcut for lm(y ~ x + x:z, data)

These two give the same results:

lm(mpg ~ disp/hp,data = mtcars)

Call:
lm(formula = mpg ~ disp/hp, data = df)

Coefficients:
(Intercept)         disp      disp:hp  
  2.932e+01   -3.751e-02   -1.433e-05  


lm(mpg ~ disp + disp:hp, data = mtcars)

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

Coefficients:
(Intercept)         disp      disp:hp  
  2.932e+01   -3.751e-02   -1.433e-05  

So, what your doing is modelling mpg based on disp alone and on an interaction between disp and hp.

Upvotes: 20

Related Questions