如何将数据框架的交互计算变量添加到新公式中

时间:2015-11-22 16:54:40

标签: r loops dataframe

我需要插入新的数值变量,这些数据变量是数据框变量的交互。我通过名称调用变量来手动设置它,但是我怎么能不通过它们的名字来调用呢?

 dat <- read.table(text = " IndexRow TargetVar  chairs    tables     lamps  vases
    1     0        0        0         7  9
    2     0        0        1         1  6 
    3     0        1        0         3  5 
    4     0        1        1         7  8 
    5     1        0        0         5  4
    6     1        0        1         1  3 
    7     1        1        0         0  7
    8     1        1        1         6  6
    9     0        0        0         8  9  ", header = TRUE) 

如果我手动输入变量,以下代码行将按预期工作: dat<-cbind(dat,data.frame(model.matrix(~(chairs+ tables)^2-1,dat))) 但我无法弄清楚如何插入变量而不用他们的名字来调用它们。 我尝试了以下两行代码而没有成功,Any Ideas如何解决这个问题?
try1:

dat<-model.matrix(~(dat[,1:ncol(dat)])^2-1,data =dat )

try2:

e<-for (i in names(dat)) function(x) {model.matrix(~(dat[,i])^2-1,dat[,i])}

1 个答案:

答案 0 :(得分:2)

子集data.frame,然后从所有变量创建主要因子和一阶交互:

as.data.frame(model.matrix(~ (. + .)^2 - 1, dat[, 3:5]))
#  chairs tables lamps chairs:tables chairs:lamps tables:lamps
#1      0      0     7             0            0            0
#2      0      1     1             0            0            1
#3      1      0     3             0            3            0
#4      1      1     7             1            7            7
#5      0      0     5             0            0            0
#6      0      1     1             0            0            1
#7      1      0     0             0            0            0
#8      1      1     6             1            6            6
#9      0      0     8             0            0            0