Home > Mobile >  Dummy coding a variable as a factor? Cannot seem to work with a package
Dummy coding a variable as a factor? Cannot seem to work with a package

Time:09-25

Trying to use a more obscure package in my field of study. I am attempting to add a matrix of predictor variables. Wording in the package is as follows:

"An optional matrix of predictor variables for the time-intensity parameters, where the columns represent the predictor variables. Cat- egorical predictor variables need to be dummy coded."

Thus I convert into factors/characters which gives the following error which I attempt to solve in the code chunk (Xit_form being a 18x2 matrix of categorical variables)

"Error in crossprod(x, y) : requires numeric/complex matrix/vector arguments "

xit_form[,1] <- as.factor(xit_form[,1])
xit_form[,2] <- as.factor(xit_form[,2])
mode(xit_form) <- "numeric"

however when i run this, the package does not seem to be treating it as a factor. Any way I can solve this?

CodePudding user response:

Maybe this is completely off, but try model.matrix.

xit_form[] <- apply(xit_form, 2, factor)
model.matrix(~ 0   ., data = as.data.frame(xit_form))

Data

set.seed(2021)
xit_form <- matrix(sample(letters[1:4], 20, TRUE), ncol = 2)

CodePudding user response:

We may use dummies from fastDummies

library(fastDummies)
library(dplyr)
xit_form %>% 
   dummy_cols()
  • Related