How to do Group By Rollup in R? (Like SQL)

后端 未结 3 470
陌清茗
陌清茗 2020-12-19 19:16

I have a dataset and I want to perform something like Group By Rollup like we have in SQL for aggregate values.

Below is a reproducible example. I k

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 19:57

    melt/dcast in the reshape2 package can do subtotalling. After running dcast we replace "(all)" in the month column with the month using na.locf from the zoo package:

    library(reshape2)
    library(zoo)
    
    m <- melt(df, measure.vars = "sales")
    dout <- dcast(m, year + month + region ~ variable, fun.aggregate = sum, margins = "month")
    
    dout$month <- na.locf(replace(dout$month, dout$month  == "(all)", NA))
    

    giving:

    > dout
      year month region sales
    1 2016     1   east   400
    2 2016     1   west   600
    3 2016     1  (all)  1000
    4 2017     2   east   800
    5 2017     2   west  1200
    6 2017     2  (all)  2000
    

提交回复
热议问题