My data is transactions like this:
ID=c("A123","A123","A123","A123","B456","B456","B456","C789","C789")
item=c("bread", "butter", "milk", "eggs", "meat","milk", "peas", "peas", "meat")
df=data.frame(cbind(ID, item))
ID item
1 A123 bread
2 A123 butter
3 A123 milk
4 A123 eggs
5 B456 meat
6 B456 milk
7 B456 peas
I want to make recommendations, so I transform the data and build rules
library(arules)
trans = as(split(df$item, df$ID), "transactions")
rules = apriori(trans, parameter = list(support = 0.006, confidence = 0.25,
minlen = 2))
Recommendation for the customer with basket 3 is found like this:
basket = trans[3]
rulesMatchLHS = is.subset(rules@lhs,basket)
suitableRules = rulesMatchLHS & !(is.subset(rules@rhs,basket))
order.rules = sort(rules[suitableRules], by = "lift")
LIST(order.rules@rhs)[[1]]
[1] "milk"
But how can I make recommendations for all baskets? I tried this, but get an error:
reco=function(x){
rulesMatchLHS = is.subset(rules@lhs,x)
suitableRules = rulesMatchLHS & !(is.subset(rules@rhs,x))
order.rules = sort(rules[suitableRules], by = "lift")
LIST(order.rules@rhs)[[1]]
}
results = lapply(trans, function(x) reco(x))
Error in as.vector(data) : no method for coercing this S4 class to a vector
How could I run the recommendations for all the baskets?
try this:
sapply(1:length(trans), function(x) reco(trans[x]))
Apparently, there is no function to convert transactions class to a vector.