One-Hot Encoding in [R] | Categorical to Dummy Variables [duplicate]

别来无恙 提交于 2019-11-27 04:15:21
dd <- read.table(text="
   RACE        AGE.BELOW.21     CLASS
   HISPANIC          0          A
   ASIAN             1          A
   HISPANIC          1          D
   CAUCASIAN         1          B",
  header=TRUE)


  with(dd,
       data.frame(model.matrix(~RACE-1,dd),
                  AGE.BELOW.21,CLASS))
 ##   RACEASIAN RACECAUCASIAN RACEHISPANIC AGE.BELOW.21 CLASS
 ## 1         0             0            1            0     A
 ## 2         1             0            0            1     A
 ## 3         0             0            1            1     D
 ## 4         0             1            0            1     B

The formula ~RACE-1 specifies that R should create dummy variables from the RACE variable, but suppress the intercept (so that each column represents whether an observation comes from a specified category); the default, without -1, is to make the first column an intercept term (all ones), omitting the dummy variable for the baseline level (first level of the factor) from the model matrix.

More generally, you might want something like

 dd0 <- subset(dd,select=-CLASS)
 data.frame(model.matrix(~.-1,dd0),CLASS=dd$CLASS)

Note that when you have multiple categorical variables you will have to something a little bit tricky if you want full sets of dummy variables for each one. I would think of cbind()ing together separate model matrices, but I think there's also some trick for doing this all at once that I forget ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!