Search code examples
rfunctiondummy-variable

Functions within R for dummy variables


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.


Solution

  • I've found a different way of creating dummies for multiple variables at the same time using the code:-

    New_Dataset<-dummy.data.frame(dataset, sep="") 
    

    Note that each variable within dataset will be changed to dummies, so it's better to separate out the variables you want as dummies.

    Sep = "" 
    

    Can be changed to whatever you want to be between the variable name and the value of the variable.