Using the data.table and gtools package, we can recreate all possible permutations by the client:
library(data.table) library(gtools) item <- c("h","h","h","j","j") customer <- c("a","a","b","b","b") test.data <- data.table(item,customer) DT <- unique(test.data) #The unique is used as multiple purchases do not count twice tuples <- function(x){ return(data.frame(permutations(length(x), 2, x, repeats.allowed = T, set = F), stringsAsFactors = F)) } DO <- DT[, tuples(item), by = customer]
This gives:
customer X1 X2 1: ahh 2: bhh 3: bhj 4: bjh 5: bjj
What is the list of all unique pairs of elements that the client has. According to your example, we handle hxj differently than jx h. Now we can get the frequency of each pair using the table function:
table(DO$X1,DO$X2) jh j 1 1 h 1 2
source share