Reconstruct a categorical variable from dummies in R

前端 未结 3 490
予麋鹿
予麋鹿 2021-01-15 16:40

Heyho, I am a beginner in R and have a problem to which I couldn\'t find a solution so far. I would like to transform dummy variables back to categorical variables.

3条回答
  •  悲哀的现实
    2021-01-15 17:15

    We can use max.col

    data.frame(dummy = names(df1)[max.col(df1)])
    #    dummy
    #1 dummy2
    #2 dummy1
    #3 dummy2
    #4 dummy3
    

    data

    df1 <- structure(list(dummy1 = c(0L, 1L, 0L, 0L), dummy2 = c(1L, 0L, 
     1L, 0L), dummy3 = c(0L, 0L, 0L, 1L)), .Names = c("dummy1", "dummy2", 
     "dummy3"), class = "data.frame", row.names = c(NA, -4L))
    

提交回复
热议问题