我希望根据财政年度将一些数据从季度汇总到每年。所以这一年将涵盖9月至6月。我可以设法在一年中汇总,但它是日历年汇总。以下示例:
Date <- seq(as.Date("1999-03-01"), as.Date("2002-12-01"), by = "quarter")
df <- data.frame(Date, value = 1:length(Date))
df %>%
mutate(Year = year(Date),
Quarter = quarter(Date)) %>%
group_by(Year) %>%
summarise(value = sum(value))
如下所示:
Year value
<dbl> <int>
1 1999 10
2 2000 26
3 2001 42
4 2002 58
但我期待这样的事情:
Date value
1 1999 3
2 2000 18
3 2001 34
4 2002 50
5 2003 31
看起来像dplyr可以处理的东西,但我无法弄明白。
答案 0 :(得分:3)
您需要再添加一列才能启用所需的分组。我喜欢使用lubridate进行日期操作:
library(tidyverse)
library(lubridate)
Date <- seq(ymd("1999-03-01"), ymd("2002-12-01"), by = "quarter")
df <- data.frame(Date, value = 1:length(Date))
df %>%
mutate(Year = year(Date),
Quarter = quarter(Date),
Finyear = ifelse(Quarter <= 2, Year, Year+1)) %>%
group_by(Finyear) %>%
summarise(value = sum(value))
&#13;