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.
Asked
Active
Viewed 1,106 times
-2
-
1This has been answered several times over at Cross Validated. You could try searching there(and here too). – NelsonGon May 07 '19 at 15:47
-
Here is an interesting [CV thread](https://stats.stackexchange.com/questions/379760/can-a-dummy-variable-take-on-more-than-2-values). It might help you. – NelsonGon May 07 '19 at 15:58
1 Answers
0
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.

Arturo Sbr
- 5,567
- 4
- 38
- 76