[R] lm() and interactions in model formula for x passed as matrix

Joshua Wiley jwiley.psych at gmail.com
Sun Dec 5 21:55:22 CET 2010


Hi Bill,

If you can put all (and only) your variables into a dataframe, (for example:
X <- data.frame(y, x1, x2, x3)
)

then another alternative to David's solution would be:

lm(y ~ .^3, data = X)

'.' will expand to every column except y, and then the ^3 will get you
up to 3-way interactions.

Cheers,

Josh

On Sun, Dec 5, 2010 at 12:19 PM, William Simpson
<william.a.simpson at gmail.com> wrote:
> Suppose I have x variables x1, x2, x3 (however in general I don't know
> how many x variables there are). I can do
> X<-cbind(x1,x2,x3)
> lm(y ~ X)
> This fits the no-interaction model with b0, b1, b2, b3.
>
> How can I get lm() to fit the model that includes interactions when I
> pass X to lm()? For my example,
> lm(y~x1*x2*x3)
> I am looking for something along the lines of
> lm(y~X ...)
> where ... is some extra stuff I need to fill in.
>
> Thanks for any help.
> Bill
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list