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).