1.下载Matrix和arules包
install.packages(c("Matrix","arules"))
2.载入引入Matrix和arules包
# 引入Matrix和arules包
library(Matrix)
library(arules)
3.读取数据
# 读入数据
dataset <- mysql_find(sql)
4.数据转换
# 将数据框转为矩阵 dataset2 <- as.matrix(dataset) # 转换为交易流数据transactions dataset2.class<-as(dataset2,"transactions")
5.调用apriori算法
rules<-apriori(dataset2.class,parameter=list(supp=0.7,conf=0.8,target="rules")) # 指定前导为item1 rules<-apriori(dataset2.class,parameter=list(supp=supp,conf=conf,target="rules"),appearance= list(rhs="item1",default="lhs"))
6.将结果保存
# 写入 write.table(inspect(rules), file = paste("app/save/aprio/",filename,".txt",sep =""), col.names = F, row.names = F, quote=F)
封装AprioriHelper.R类
# 引入Matrix和arules库 library(Matrix) library(arules) # 引入脚本文件 source('Helper/mysql_helper.R', encoding = 'UTF-8') # 构建aprio函数 aprio <- function(sql,supp,conf,filename){ # 读入数据 dataset <- mysql_find(sql)[,3:17] # 修改列名 names(dataset) <- c("item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10", "item11", "item12", "item13", "item14", "item15") # 将数据框转为矩阵 dataset2 <- as.matrix(dataset) # 转换为交易流数据transactions dataset2.class<-as(dataset2,"transactions") # 调用apriori算法 if(filename=="all"){ rules<-apriori(dataset2.class,parameter=list(supp=supp,conf=conf,target="rules")) }else{ rules<-apriori(dataset2.class,parameter=list(supp=supp,conf=conf,target="rules"),appearance= list(rhs="item1",default="lhs")) } # 写入 write.table(inspect(rules), file = paste("app/save/aprio/",filename,".txt",sep =""), col.names = F, row.names = F, quote=F) }