spindoctor
spindoctor

Reputation: 1895

fit an interaction term to each preceding variable

Is there a way in R to fit an interaction term to each preceding variable in the model specification? I would like to do the following, but in a more concise way.


data("mtcars")
head(mtcars)
mod1<-lm(mpg~ cyl+disp+hp+wt+cyl:wt+disp:wt+hp:wt, data=mtcars)
summary(mod1)

Upvotes: 1

Views: 31

Answers (2)

jay.sf
jay.sf

Reputation: 72813

It's similar to arithmetic.

f1 <- lm(mpg ~ cyl + disp + hp + wt + cyl:wt + disp:wt + hp:wt, data=mtcars)
f2 <- lm(mpg ~ (cyl + disp + hp)*wt, data=mtcars)

stopifnot(all.equal(f1$coe, f2$coe))

Upvotes: 1

Austin Graves
Austin Graves

Reputation: 1052

I think this should do the trick.

mod1<-lm(mpg~ (cyl+disp+hp+wt)^2, data=mtcars)

Upvotes: 0

Related Questions