Search code examples
rdummy-variable

Creating dummy variables for more than 2 levels


How do I create dummy variables for more than two levels for categorical data in r? I tried model.matrix but it didn’t work.


Solution

  • Read your coulmn as class factor.

    Suppose your data is stored in df and categories has the categories you want to convert to dummies. Then:

    df$categories <- as.factor(df$categories)
    

    You will not see new columns created. The factor class is a shortcut for this kind of task. Try running a regression model like this and you'll see the results.