R arules为事务准备数据集

时间:2016-10-30 05:10:37

标签: r transactions arules

我准备了一个数据集,用于在R中使用arules包作为事务读取它。但是,当我使用命令itemFrequencyplot时,我的一个数据预处理导致了一个问题,具体来说,最高频率项是“”。有人会有任何建议来解决这个问题吗?

原始数据:

data <- as.data.frame(matrix(NA, nrow = 10, ncol = 3))
colnames(data) <- c("Customer", "OrderDate", "Product")
data$Customer <- c("John", "John", "John", "Tom", "Tom", "Tom", "Sally", "Sally", "Sally", "Sally")
data$OrderDate <- c("1-Oct", "2-Oct", "2-Oct", "2-Oct","2-Oct", "2-Oct", "3-Oct", "3-Oct", "3-Oct", "3-Oct")
data$Product <- c("Milk", "Eggs", "Bread", "Butter", "Eggs", "Milk", "Bread", "Butter", "Eggs", "Wine")

我进行了以下转换

library(reshape2)
library(dplyr)

newdata <- data  %>% 
  group_by(Customer, OrderDate) %>%
  mutate(ProductValue = paste0("Product", 1:n()) ) %>%
  dcast(Customer + OrderDate ~ ProductValue, value.var = "Product") %>%
  arrange(OrderDate)

newdata[is.na(newdata)] <- " "
newdata <- newdata[ , 3:6]
newdata[sapply(newdata, is.character)] <- lapply(newdata[sapply(newdata, is.character)], as.factor) #converting is.character columns into as.factor

使用write.table创建没有列名的csv文件,以便通过arules读取

write.table(newdata, "transactions.csv", row.names = FALSE, col.names = FALSE, sep = ",") 

使用arules包将csv文件作为事务读取

library(arules)

transactiondata <- read.transactions("transactions.csv", sep = ",", format = "basket") 

不起作用 - 抛出错误,在读取stackoverflow上的先前查询后,我能够按如下方式解决它

transactiondata <- read.transactions("transactions.csv", sep = ",", format = "basket", rm.duplicates = TRUE)

itemFrequencyPlot(transactiondata, topN = 5)

该图的结果具有“”作为顶部频率项,实际上并非如此,并且是我的数据预处理的结果。我们将非常感谢您解决此问题的建议!

1 个答案:

答案 0 :(得分:1)

我会这样做(按照交易手册页中的示例):

data_list <- split(data$Product, paste(data$OrderDate, data$Customer))
trans <- as(data_list, "transactions")
inspect(trans)

    items                    transactionID
[1] {Milk}                   1-Oct John   
[2] {Bread,Eggs}             2-Oct John   
[3] {Butter,Eggs,Milk}       2-Oct Tom    
[4] {Bread,Butter,Eggs,Wine} 3-Oct Sally

itemFrequencyPlot(trans, topN = 5)

希望这有帮助!