In base R I would suggest ave
:
within(mydf, {
count = ave(Product, Customer, FUN = function(x) length(unique(x)))
})
## Customer Product count
## 1 1 Chocolate 3
## 2 1 Candy 3
## 3 1 Soda 3
## 4 2 Chocolate 1
## 5 2 Chocolate 1
## 6 2 Chocolate 1
## 7 3 Insulin 2
## 8 3 Candy 2
You could also try the "data.table" package:
library(data.table)
as.data.table(mydf)[, count := length(unique(Product)), by = Customer][]
## Customer Product count
## 1: 1 Chocolate 3
## 2: 1 Candy 3
## 3: 1 Soda 3
## 4: 2 Chocolate 1
## 5: 2 Chocolate 1
## 6: 2 Chocolate 1
## 7: 3 Insulin 2
## 8: 3 Candy 2