0

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.

Miha
  • 2,559
  • 2
  • 19
  • 34
MLPNPC
  • 454
  • 5
  • 18
  • You must substitute `Input1` with a name in the formula. If you provide a reproducible example we can show you how. – Roland Oct 17 '17 at 08:47
  • I thought that is what I was doing with : Disability<-dummy_vars("Disability") The "Disability" would be Input1? – MLPNPC Oct 17 '17 at 08:50
  • `"Disability"` is just a character string, not the name of a column in some unspecified data frame, your function knows nothing about that df. You could try making `Input1 = get("Disability")`. (I'm not sure that this works.) – Rui Barradas Oct 17 '17 at 09:39
  • 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 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. – MLPNPC Oct 18 '17 at 14:34

1 Answers1

0

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.

MLPNPC
  • 454
  • 5
  • 18