将字符向量转换为arules的事务

时间:2017-09-05 09:59:12

标签: r apriori arules

请帮助将购物商品的字符向量转换为"交易"对于arules。原始数据类似于:

shopping_items <- c("apple banana", "orange", "tea orange beef")

向量的每个元素表示在单个事务中购买的项目,并且项目由空格分隔。 &#34;,例如,交易1包括两个项目,即苹果和香蕉。如何将其转换为&#34;交易&#34;输入以便我可以在arules中使用它?

提前谢谢!

2 个答案:

答案 0 :(得分:2)

实施可能不是最佳的,但您可以尝试改进它。

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, ...

答案 1 :(得分:2)

这是简短版本:

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}