Another idea,
library(dplyr)
library(tidyr)
df %>%
unnest(y) %>%
mutate(new = 1) %>%
spread(y, new, fill = 0)
# x A B C D E
#1 1 1 0 0 0 0
#2 2 1 1 0 0 0
#3 3 0 0 1 0 0
#4 4 0 1 1 1 0
#5 5 0 0 0 0 1
Further to the cases you mentioned in comments, we can use dcast
from reshape2
as it is more flexible than spread
,
df2 <- df %>%
unnest(y) %>%
group_by(x) %>%
filter(!duplicated(y)) %>%
ungroup()
reshape2::dcast(df2, x ~ y, value.var = 'y', length)
# x A B C D E
#1 1 1 0 0 0 0
#2 2 1 1 0 0 0
#3 3 0 0 1 0 0
#4 4 0 1 1 1 0
#5 5 0 0 0 0 1
#or with df$x <- c(1, 1, 2, 2, 3)
# x A B C D E
#1 1 1 1 0 0 0
#2 2 0 1 1 1 0
#3 3 0 0 0 0 1
#or with df$x <- rep(1,5)
# x A B C D E
#1 1 1 1 1 1 1