如何按月对多个数据框的变量求和

时间:2017-09-28 08:53:25

标签: r date sum

我在这里解决了一个非常类似的问题how to sum data by month and store them in the first day of the month

唯一与上述帖子不同的是,我的真实data.frame有300个变量需要按月分组和求和。

这样的事情:

    date        gauge1   gauge2  gauge3
 1937-02-19   25.768334  23.98   111.3
 1937-02-20   24.918828  21.987  33.9
 1937-02-21   24.069322  19.96   18.981

期望的输出:

 date         gauge1    gauge2   gauge3
 1937-02-01   3328.98   2229.0   11541.3
 1937-03-01   222.19    1176.8   1098.8
 1937-04-01   1124.8    3395.15  1558.9

根据@jeremycg的回答我试过了:

library(dplyr)
qfile %>% mutate(monthyear = as.character(format(date, "%m-%Y"))) %>%
          arrange(date) %>% 
          group_by(monthyear) %>%
          summarise(date=date[1], flow = sum(df[, c(2:4)])

但它不起作用。

任何帮助都会非常感激。

由于

1 个答案:

答案 0 :(得分:2)

如果除了student列以外的所有列都需要进行分组和求和,您可以尝试:

date
library(data.table)
setDT(qfile)[, lapply(.SD, sum), by = lubridate::floor_date(date, "month")]

或者,如果要重命名分组变量:

    lubridate   gauge1 gauge2  gauge3
1: 1937-02-01 74.75648 65.927 164.181
setDT(qfile)[, lapply(.SD, sum), by = (date = lubridate::floor_date(date, "month"))]

按照@Henrik的建议,使用 date gauge1 gauge2 gauge3 1: 1937-02-01 74.75648 65.927 164.181 的内置data.table函数可以避免从另一个包调用函数:

mday()