首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符向量转换为arules的事务

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

Stack Overflow用户
提问于 2017-09-05 09:59:11
回答 2查看 669关注 0票数 0

请帮助将购物项目的字符向量转换为arules的"transactions“。原始数据如下:

代码语言:javascript
复制
shopping_items <- c("apple banana", "orange", "tea orange beef")

向量中的每个元素表示在单个事务中购买的项目,项目由空格“”分隔,例如,transaction 1包含两个项目,即苹果和香蕉。我如何将它转换为“事务”类型,以便我可以在arules中使用它?

提前谢谢你!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-05 22:14:34

这是一个简短的版本:

代码语言:javascript
复制
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}
票数 2
EN

Stack Overflow用户

发布于 2017-09-05 11:31:32

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

代码语言:javascript
复制
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, ...
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46052187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档