I'm wanting to create dummy variables for a few different columns in R. I can do this for the variable Disability with the code:
Disability <- model.matrix(~ Disability - 1,
transform(Dev_Mod, Disability = factor(paste(Disability, sep = "_"))))
Because I want to run this code multiple times for various variables I'd prefer to create a function for this, so I've written the function below:
dummy_vars <- function(Input1){
output <- model.matrix(~ Input1 - 1,
transform(Dev_Mod, Input1 = factor(paste(Input1, sep = "_"))))
return(output)
}
When I then run:
Disability <- dummy_vars("Disability")
I get the error
Error in
contrasts<-
(*tmp*
, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels
I've tried this for multiple variables and I get the same error for each one.
I've checked and they definitely have 2 or more levels so I don't understand how to the fix the error.