This question already has an answer here:
- Table of Interactions - Case with pets and houses 1 answer
I have data that shows what customers have purchased certain items. They can purchase an item multiple times. What I need is a table that shows all of the possible pairwise combinations of items along with the unique number of customers who have purchased that combination (the diagonal of the table will just be the unique number of people purchasing each item).
Here is an example:
item <- c("h","h","h","j","j")
customer <- c("a","a","b","b","b")
test.data <- data.frame(item,customer)
Here is the test.data:
item customer
h a
h a
h b
j b
j b
Result needed - a table with the items as row and column names, with the counts of unique customers purchasing the pair inside the table. So, 2 customers purchased item h, 1 purchased both item h and j, and 1 purchased item j.
item h j
h 2 1
j 1 1
I have tried using the table function, melt
/cast
, etc., but nothing gets me the counts I need within the table. My first step is using unique()
to get rid of duplicate rows.