【问题标题】:Reshape Long to Wide aggregating by 2 variables [duplicate]通过 2 个变量将 Long 聚合到 Wide 聚合
【发布时间】:2017-10-26 14:59:05
【问题描述】:

我想通过 2 个变量(其组合创建新的唯一标识符)将我的数据框从长到宽重塑,同时按产品、产品 2 和日期聚合值,以便如下:

Date           product product2 value
03/03/2011       a        z        7
03/03/2011       a        z        2
03/05/2015       b        z       89
03/01/2017       a        z        2
03/03/2017       c        z        6

这将产生以下内容:

      03/03/2011  03/03/2011  03/05/2015  03/01/2017  03/03/2017 
a z       9                                   2
b z                               89
c z                                                        6

我应该使用 dplyr、reshape、reshape2 吗?

df <- structure(list(Date = c("03/03/2011", "03/03/2011", "03/05/2015", "03/01/2017", "03/03/2017"),
             product= c("a", "a", "b", "a", "c"),
             product2= c("z", "z", "z", "z", "z"), 
             value= c(7L, 2L, 89L, 2L, 6L)), 
             .Names= c("Date", "product", "product2", "value"), 
             class= "data.frame", row.names=c(NA, -5L))

【问题讨论】:

    标签: r time aggregate reshape


    【解决方案1】:
    library(data.table)
    data<-fread("Date           product product2 value
    03/03/2011       a        z        7
                03/03/2011       a        z        2
                03/05/2015       b        z       89
                03/01/2017       a        z        2
                03/03/2017       c        z        6")
    data<-dcast(data,product+product2~Date,value.var="value",fun.aggregate = sum)
    data[,unique_id:=paste(product,product2,sep="")]
    data
       product product2 03/01/2017 03/03/2011 03/03/2017 03/05/2015 unique_id
    1:       a        z          2          9          0          0        az
    2:       b        z          0          0          0         89        bz
    3:       c        z          0          0          6          0        cz
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多