【问题标题】:How to convert data into transactional format in R如何在R中将数据转换为事务格式
【发布时间】:2020-10-21 23:54:16
【问题描述】:

我有以下数据集,我想将其转换为事务格式。

sample_data<-data.frame(id=c(452,125,288,496,785,328,712,647),a=c(5,8,7,9,0,0,4,0),b=c(0,7,8,9,3,6,0,0),c=c(7,8,9,0,0,0,0,7),d=c(8,7,5,0,0,0,0,7))
sample_data

sample_data
id  a b c d
452 5 0 7 8
125 8 7 8 7
288 7 8 9 5
496 9 9 0 0
785 0 3 0 0
328 0 6 0 0
712 4 0 0 0
647 0 0 7 7

想要的输出如下:

id      item
452     a c d
125     a b c d
288     a b c d
496     a b
785     b
328     b
712     a
647     c d

如何在 R 中实现这一点?

有没有更简单的方法?

【问题讨论】:

    标签: r dataframe apriori


    【解决方案1】:

    这是使用pivot_longerfiltersummarizetidyverse 解决方案。

    library(dplyr)
    library(stringr)
    library(tidyr)
    
    sample_data %>%
      pivot_longer(a:d, names_to = "item") %>%
      filter(value != 0) %>%
      group_by(id) %>%
      summarize(item = str_c(item, collapse = " "))
    
    # A tibble: 8 x 2
         id item   
      <dbl> <chr>  
    1   125 a b c d
    2   288 a b c d
    3   328 b      
    4   452 a c d  
    5   496 a b    
    6   647 c d    
    7   712 a      
    8   785 b    
    

    【讨论】:

      【解决方案2】:

      我们可以用apply遍历行,得到数值列值不为0的数据的namespaste一起,然后cbind和第一列数据

      cbind(sample_data[1], item = apply(sample_data[-1], 1, 
            function(x) paste(names(x)[x != 0], collapse = ' ')))
      

      -输出

      #   id    item
      #1 452   a c d
      #2 125 a b c d
      #3 288 a b c d
      #4 496     a b
      #5 785       b
      #6 328       b
      #7 712       a
      #8 647     c d
      

      【讨论】:

        猜你喜欢
        • 2023-03-25
        • 2017-12-27
        • 1970-01-01
        • 2019-04-13
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 2021-11-16
        相关资源
        最近更新 更多