rmodel.matrix

Model matrix with n-wise interactions between all variables


I am using the following code to create n-order interactions between variables in a data set. For the case of second-order interactions, I use:

train_X <- model.matrix(~.^2, train_data %>% select(-target))

That worked properly, nevertheless, when I try to make the n-order term modular to embed this code within a function in the following way, it does not work:

n <- 2
train_X <- model.matrix(~.^n, train_data %>% select(-target))

Particularly, it returns the following error:

Error in terms.formula(object, data = data) : invalid power in formula

I have also tried to specify n = 2L, but it returns the same error.


Solution

  • try building your formula as a string (using paste(), glue::glue(), sprintf(), or whatever your like) and converting to a formula (using as.formula() or reformulate()).

    train_X <- model.matrix(
       as.formula(sprintf("~.^%d", n)), 
       train_data %>% select(-target))