Reputation: 2243
I need to insert new numeric variables that are Interactions of the data frame's variables.I managed to it manually by calling the variables by names but how can I do it without calling them by thier names?
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)
If I enter the variables manually the following line of code will work as expected:
dat<-cbind(dat,data.frame(model.matrix(~(chairs+ tables)^2-1,dat)))
But I can't figuring out how to insert the variables without calling them by thier names.
I tried the following two lines of code with out success, Any Ideas how to solve this issue?
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])}
Upvotes: 0
Views: 603
Reputation: 132969
Subset the data.frame and then create main factors and first-order interactions from all variables:
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
Upvotes: 2