Reputation: 199
I have 100 categorical variables in a dataframe and I want to create interactions for my predictive models. I created a loop to do it but I end up getting duplicates.
df <- data.frame(Col1=c("A","B","C"),
Col2=c("F","G","H"),
Col3=c("X","Y","Z"))
Which gives us:
Col1 Col2 Col3
1 A F X
2 B G Y
3 C H Z
When I run the code to create interactions variables with
vars <- colnames(df)
for (i in vars) {
for (j in vars) {
if (i != j) {
df[,c(paste0(i, j))] <- paste(df[[i]],df[[j]],sep='*')}}}
I end up with dups such as Col1Col2 is the same as Col2Col1.
> str(df)
'data.frame': 3 obs. of 9 variables:
$ Col1 : Factor w/ 3 levels "A","B","C": 1 2 3
$ Col2 : Factor w/ 3 levels "F","G","H": 1 2 3
$ Col3 : Factor w/ 3 levels "X","Y","Z": 1 2 3
$ Col1Col2: chr "A*F" "B*G" "C*H"
$ Col1Col3: chr "A*X" "B*Y" "C*Z"
$ Col2Col1: chr "F*A" "G*B" "H*C"
$ Col2Col3: chr "F*X" "G*Y" "H*Z"
$ Col3Col1: chr "X*A" "Y*B" "Z*C"
$ Col3Col2: chr "X*F" "Y*G" "Z*H"
Is there a way to remove these dups?
Upvotes: 3
Views: 1149
Reputation: 93871
You don't need to create an explicit interaction column for each pair of variables. Instead Col1 * Col2
in a model formula will generate the interactions automatically. For example, if your outcome variable is y
(which would be a column in your data frame), and you want a regression formula with all two-way interactions between the other columns, you could do:
form = reformulate(apply(combn(names(df)[-grep("y", names(df))], 2), 2, paste, collapse="*"), "y")
form
y ~ Col1 * Col2 + Col1 * Col3 + Col2 * Col3
Then your regression model would be:
mod = lm(form, data=df)
Upvotes: 2
Reputation: 20095
One option could be using combn
and apply
functions. One custom function will be need to print two categorical values separated by *
(e.g. A*F
).
# data
df <- data.frame(Col1=c("A","B","C"),
Col2=c("F","G","H"),
Col3=c("X","Y","Z"))
#function to paste two values together in A*F format
multiplyit <- function(x){
paste(x, collapse = "*")
}
# Call combn using apply
df2 <- t(apply(df, 1, combn, 2, multiplyit))
#generate and set column names of df2
colnames(df2) <- paste("Col", combn(1:3, 2, paste, collapse="Col"), sep="")
#combine df and df2 to get the final df
df_final <- cbind(df, df2)
df_final
# Col1 Col2 Col3 Col1Col2 Col1Col3 Col2Col3
#1 A F X A*F A*X F*X
#2 B G Y B*G B*Y G*Y
#3 C H Z C*H C*Z H*Z
Upvotes: 0
Reputation: 1373
Possible answer to your question: How to automatically include all 2-way interactions in a glm model in R
You can do two-way interactions simply using `.*.` and arbitrary n-way interactions writing `.^n`. `formula(g)` will tell you the expanded version of the formula in each of these cases.
Upvotes: 0