Reconstruct a categorical variable from dummies in R

前端 未结 3 523
予麋鹿
予麋鹿 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:26

    Here is a tidyverse solution, using tidyr::gather. Here we treat the key as the variable that each dummy is a category of, and value as the presence/absence. Replacing 0 with NA combined with na.rm = TRUE in gather means we don't keep all the rest of the rows we don't want and don't create an unnecessarily large intermediate dataset.

    df1 <- structure(list(dummy1 = c(0L, 1L, 0L, 0L), dummy2 = c(1L, 0L, 
                                                                 1L, 0L), dummy3 = c(0L, 0L, 0L, 1L), ed1 = c(1, 0, 1, 0), ed2 = c(0, 
                                                                                                                                   1, 0, 1), id = c(1, 2, 3, 4)), .Names = c("dummy1", "dummy2", 
                                                                                                                                                                             "dummy3", "ed1", "ed2", "id"), row.names = c(NA, -4L), class = "data.frame")
    library(tidyverse)
    df1 %>%
      mutate_at(vars(dummy1:dummy3, ed1:ed2), ~ ifelse(. == 0, NA, .)) %>%
      gather("dummy", "present", dummy1:dummy3, na.rm = TRUE) %>%
      gather("ed", "present2", ed1:ed2, na.rm = TRUE) %>%
      select(-present, -present2)
    #>   id  dummy  ed
    #> 2  1 dummy2 ed1
    #> 3  3 dummy2 ed1
    #> 5  2 dummy1 ed2
    #> 8  4 dummy3 ed2
    

    Created on 2018-03-06 by the reprex package (v0.2.0).

提交回复
热议问题