This is achieved by the fact that you after
library(data.table)
mydt <- data.table(User = c("Alice", "Alice", "Bob", "Charlotte"),
Movie = c("Fight Club", "The Godfather", "Titanic", "The Godfather"))
mydt2 <- data.table(t(mydt[,combn(unique(Movie), 2, simplify = FALSE)]))
names(mydt2) <- c("Movie1", "Movie2")
temp <- apply(mydt2, 1, function(x) mydt[Movie %in% x, .N, by = User])
mydt2[, WatchedOne := lapply(temp, function(x) x[, length(N)])]
mydt2[, WatchedBoth := lapply(temp, function(x) x[, sum(N==2)])]
source
share