【问题标题】:Converting multiple row data to single row in R/Excel [duplicate]在R / Excel中将多行数据转换为单行[重复]
【发布时间】:2015-03-18 10:13:51
【问题描述】:

我正在为 Market Basket Analysis 处理交易数据,该数据具有以下提到的表格格式:

Id Product    
 1  Prod A    
 1  Prod B    
 1  Prod C    
 1  Prod D   
 2  Prod A    
 2  Prod B

我想转换数据的布局,以便先验算法可以工作,将数据作为单个事务数据。因此,出于此目的,我想将数据转换为以下格式:

Id Column1 Column2 Column3 Column3    
 1  Prod A  Prod B  Prod C  Prod D    
 2  Prod A  Prod B
  1. 谁能帮我在 R 或 Excel 中转换这些数据?

  2. 这些数据是否适用于在 R 中运行先验算法(希望它会起作用)?

【问题讨论】:

    标签: r excel apriori market-basket-analysis


    【解决方案1】:

    R 中使用reshape2 包中的dcast

    df <- data.frame(Id=c(1,1,1,1,2,2), Product=c("Prod A", "Prod B", "Prod C", "Prod D", "Prod A", "Prod B"))
    
    library(reshape2)
    dcast(df, Id~Product, value.var="Product")
    #    Id Prod A Prod B Prod C Prod D
    #  1  1 Prod A Prod B Prod C Prod D
    #  2  2 Prod A Prod B   <NA>   <NA>
    

    【讨论】:

      【解决方案2】:
      ID <- c(1,1,1,1,2,2)
      Product <- c("Prod A","Prod B","Prod C","Prod D","Prod A","Prod B")
      df <- data.frame (ID, Product)
      

      您可以使用为第 2 步创建假人

      > xtabs(~ID  +Product, df)
      
       ID Prod A Prod B Prod C Prod D
        1      1      1      1      1
        2      1      1      0      0
      

      第二步,可以使用包arules

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-17
        • 2016-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-13
        相关资源
        最近更新 更多