请帮助将购物项目的字符向量转换为arules的"transactions“。原始数据如下:
shopping_items <- c("apple banana", "orange", "tea orange beef")向量中的每个元素表示在单个事务中购买的项目,项目由空格“”分隔,例如,transaction 1包含两个项目,即苹果和香蕉。我如何将它转换为“事务”类型,以便我可以在arules中使用它?
提前谢谢你!
发布于 2017-09-05 22:14:34
这是一个简短的版本:
library(arules)
shopping_items <- c("apple banana", "orange", "tea orange beef")
trans <- as(strsplit(shopping_items, " "), "transactions")
inspect(trans)
items
[1] {apple,banana}
[2] {orange}
[3] {beef,orange,tea}发布于 2017-09-05 11:31:32
实现可能不是最优的,但您可以尝试改进它。
library(stringi)
library(arules)
library(purrr)
shopping_items <- c("apple banana", "orange", "tea orange beef")
str <- paste(shopping_items,collapse = ' ')
# unique items
str_un <- unique(unlist(stri_split_fixed(str,' ')))
# create a dataframe with dimensions:
# length(shopping_items) x length(str_un)
df <- as.data.frame(matrix(rep(0,length(str_un)*length(shopping_items )),ncol=length(str_un)))
names(df) <- str_un
# positions of 1's in each column
vecs <- map(str_un,grep,shopping_items)
sapply(1:length(str_un), function(x) df[,x][vecs[[x]]] <<- 1)
df[] <- lapply(df,as.factor)
# Generate a transactions dataset.
tr <- as(df, "transactions")
# Generate the association rules.
# rules <- apriori(tr, ...https://stackoverflow.com/questions/46052187
复制相似问题