【问题标题】:convert character vector to transactions for arules将字符向量转换为规则的事务
【发布时间】:2017-09-05 09:59:11
【问题描述】:

请帮助将购物项目的字符向量转换为 arules 的“交易”。原始数据是这样的:

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

向量的每个元素代表单笔交易中购买的物品,物品之间用空格“ ”隔开,例如交易1包括苹果和香蕉两件物品。如何将其转换为“事务”类型以便我可以在 arules 中使用它?

提前谢谢你!

【问题讨论】:

    标签: r apriori arules


    【解决方案1】:

    这是简短的版本:

    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】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        相关资源
        最近更新 更多