问题描述
我有初步的每月签证数据(2017 年 9 月至 2020 年 11 月),我想将其与官方公布的财政年度数字进行比较。我将月份存储为 yearmon 对象,并希望在新列中标识联邦财政年度(从 10 月开始)。
我可以使用以下代码轻松完成此操作:
library(tidyverse)
library(zoo)
IVdata_FY <- IVdata_final %>%
mutate(
fy = case_when(
month <= "Sep 2017" ~ "FY17",month >= "Oct 2017" & month <= "Sep 2018" ~ "FY18",month >= "Oct 2018" & month <= "Sep 2019" ~ "FY19",month >= "Oct 2019" & month <= "Sep 2020" ~ "FY20",month >= "Oct 2020" ~ "FY21"
)
)
但是,如果我有跨越更多财政年度的数据,这种手工方法会过度且容易出错。
是否有一种简单的方法来确定财政年度,而无需详细说明每个财政年度的时间范围?我的预感是它会涉及 zoo 如何存储 yearmon 数据,但我一直无法弄清楚我可以使用哪些代码。
解决方法
您可以从 zoo
对象中提取年份和月份,如果月份大于 10 月,则将 year
值增加 1。
library(dplyr)
library(lubridate)
IVdata_final %>%
mutate(date = month,year = year(date),month = month(date),fy = paste0('FY',ifelse(month >= 10,year + 1,year))) -> IVdata_FY
IVdata_FY
,
我们假设会计年度在 9 月结束,因此 10 月、11 月和 12 月对应的会计年度是下一个日历年,其他月份的会计年度与日历年相同。
通过向输入 yearmon
对象添加 3/12 将输入向前推三个月,以便 10 月、11 月和 12 月被推入下一个日历年,但没有其他月份,然后格式化:
library(zoo)
ym <- yearmon(2020 + 0:11/12) # test data: Jan '20,Feb '20,...,Dec '20
format(ym + 3/12,"FY%y")
## [1] "FY20" "FY20" "FY20" "FY20" "FY20" "FY20" "FY20" "FY20" "FY20" "FY21"
## [11] "FY21" "FY21"