dplyr 财政年度的季度

quarter to annual dplyr financial years

我想根据财政年度从季度到年度汇总一些数据。因此,这一年将涵盖 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 可以处理,但我无法弄清楚。

您需要再添加一列以启用所需的分组。我喜欢使用 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))