An updated tidyr
-based option is to convert to long-shape, use complete
to fill in missing combinations of movies and actors, and then just convert a logical is.na
test to a numeric value. Then reshape back to wide.
library(tidyr)
mydata %>%
pivot_longer(starts_with("actor"), names_to = "acted") %>%
complete(movie, value) %>%
dplyr::mutate(acted = as.numeric(!is.na(acted))) %>%
pivot_wider(names_from = value, values_from = acted)
#> # A tibble: 2 x 4
#> movie Jack Leo Kate
#> <fct> <dbl> <dbl> <dbl>
#> 1 Departed 1 1 0
#> 2 Titanic 0 1 1