R 将月度数据汇总到季度数据

R 将月度数据汇总到季度数据,r,data.table,R,Data.table,我想有一个函数,通过取平均值将月度数据转换为季度数据。例如: 一月十日 二月五日 3月15日 那么第一季度的值将是平均值(10,5,15)=10。 我想我想出了一个解决方案,可以很容易地解决这个问题,但我有一个小问题,就是用一般的方法来解决: library(data.table) date <- seq(as.Date('2000-01-01'), as.Date('2020-04-01'), by = '1 month') x <- rnorm(244) df1 <- d

我想有一个函数,通过取平均值将月度数据转换为季度数据。例如:

一月十日

二月五日

3月15日

那么第一季度的值将是
平均值(10,5,15)=10。

我想我想出了一个解决方案,可以很容易地解决这个问题,但我有一个小问题,就是用一般的方法来解决:

library(data.table)

date <- seq(as.Date('2000-01-01'), as.Date('2020-04-01'), by = '1 month')
x <- rnorm(244)
df1 <- data.frame(date, x)

aggregate <- function(data){
  setDT(data)
  data[, mean(x), keyby = .(year(date), quarter(date))]
}

aggregate(df1) 
库(data.table)
日期可能的解决方案:

agg_quarter <- function(data, datecol, valuecol) {
  setDT(data)
  data[, mean(get(valuecol)), keyby = .(year(get(datecol)), quarter(get(datecol)))]
}
给出:


根据@John的评论,您可以将其作为一个单变量函数,但这需要您事先知道要使用哪个列。更好的方法可能是在上面的函数中使用默认参数:

agg_quarter <- function(data, datecol = "date", valuecol = "x") {
  setDT(data)
  data[, mean(get(valuecol)), keyby = .(year(get(datecol)), quarter(get(datecol)))]
}
如果datacolumn和valuecolumn具有其他名称,则仍然可以使用此函数。您需要使用以下函数(与答案的第一部分相同):


请注意,
aggregate()
已经是一个基本函数,用自定义函数来掩盖它不是一个好的工作流。谢谢!但真的没有办法用单变量函数来实现吗?
    year quarter           V1
 1: 2000       1  0.668280150
 2: 2000       2 -0.432287287
 3: 2000       3 -0.063654477
 4: 2000       4 -0.036998919
 5: 2001       1  0.003495954
....
78: 2019       2  0.441275470
79: 2019       3  0.435215828
80: 2019       4  0.561908069
81: 2020       1 -0.454111862
82: 2020       2 -1.486324939
agg_quarter <- function(data, datecol = "date", valuecol = "x") {
  setDT(data)
  data[, mean(get(valuecol)), keyby = .(year(get(datecol)), quarter(get(datecol)))]
}
agg_quarter(df1)
agg_quarter(df1, datecol = "other_date", valuecol = "other_x")