【问题标题】:R arules preparing dataset for transactionsR arules 为交易准备数据集
【发布时间】:2016-10-30 05:10:37
【问题描述】:

我准备了一个数据集,以便使用 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)

此图的结果以“”为最高频率项,实际上并非如此,这是我的数据预处理的结果。解决它的建议将不胜感激!

【问题讨论】:

  • 您使用的软件包版本是什么?当我绘制项目频率时,我会得到鸡蛋、面包、黄油、牛奶和葡萄酒。
  • 我从 v1.2 和 v1.5 更新并解决了问题

标签: r transactions arules


【解决方案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)

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多