fairly new to R here. I am looking to mine association rules in R for specific items, but I want to vary the minimum support target for these rules by each item (i.e. 10% of the item's total frequency in the transaction list). Each item has a different amount of transactions so I believe there is value in varying the support.
I've calculated the support targets for each item in a separate spreadsheet using Excel.
I can do this manually writing the arules code and manually inputting support minimum and item appearances, but the process is slow, especially with many different items.
ex.
arules <- apriori(trans, parameter = list(sup = 0.001, conf = 0.25,target="rules"),
appearance=list(rhs= c("Apples")))
arules2 <- apriori(trans, parameter = list(sup = 0.002, conf = 0.25,target="rules"),
appearance=list(rhs= c("Oranges")))
combined <- c(arules,arules2)
How can I do this using a for loop in R that will calculate the rules for each specified item at a specific support minimum, and also save those generated rules to a new variable each time the loop runs? I intend to later group these rules depending on their type.
Tried something like this which looped through too many times. I also couldn't figure out a way to save each loop to a new variable (i.e. arules1, arules2, arules3....)
min_supp <- c(0.001,0.002,0.003)
names <- c("Apples","Oranges","Grape")
for (inames in names) {
for (supports in min_supp) {
apriori(trans, parameter = list(sup = supports, conf = 0.25,target="rules"),
appearance=list(rhs= inames))
}}
Thanks in advance!
Consider Map
(the simplified wrapper to mapply
) that can iterate elementwise through same length vectors for a multiple apply method. Additionally, Map
will output a list of the returned items which can be named with setNames
. Lists are always preferred as you avoid separate, similarly structured objects flooding global environment.
min_supp <- c(0.001,0.002,0.003)
names <- c("Apples","Oranges","Grape")
arules_fun <- function(n, s) apriori(trans, parameter = list(sup = s, conf = 0.25, target="rules"),
appearance=list(rhs= n))
# PROCESS FUNCTION ELEMENTWISE
arules_list <- Map(arules_fun, names, min_supp)
# NAME LIST ITEMS
arules_list <- setNames(arules_list, paste0("arules", 1:length(arules_list)))
arules_list$arules1
arules_list$arules2
arules_list$arules3
...