r - The ways to construct columns associated with interaction terms in data frame -


i have data frame 6 columns,

dat<-data.frame(x1,x2,x3,x4,x5,x6) 

right now, need build 2 columns associated interaction terms, x1*x2 , x3*x4*x5 how in r. there special consideration when of them, such x2 categorical?

i guess function model.matrix want.

for instance, can fit linear model including variables , interaction terms you're interested in , extract model matrix fitted object

model.matrix(lm(drat ~ mpg * cyl + disp * hp * wt, data = mtcars)) 

factors need explicitly coded factors, find example below

mtcars$cyl <- factor(mtcars$cyl) model.matrix(lm(drat ~ mpg * cyl + disp * hp * wt, data = mtcars)) 

the default kind of contrasts used factors treatment coding. can change sum coding (or other codings: ?contr.sum) using command below

contrasts(mtcars$cyl) <- contr.sum 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -