Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

zoo - Identify fiscal year for yearmon object in R

I have preliminary monthly visa data (September 2017 - November 2020) that I want to compare with the official, published fiscal year numbers. I have the month stored as a yearmon object and want to identify the federal fiscal year (begins in October) in a new column.

I was able to do so easily enough with the following code:

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"
    )
  )

However, if I had data spanning more fiscal years this by-hand approach would be excessive and prone to mistakes.

Is there a simple way to identify the fiscal year without having to spell out the time frames for each one? My hunch is that it would involve how zoo stores the yearmon data, but I haven't been able to figure out what code I could use.

question from:https://stackoverflow.com/questions/65546225/identify-fiscal-year-for-yearmon-object-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We assume that the fiscal year ends in September so that the fiscal year corresponding to October, November and December is the following calendar year and for other months the fiscal year is the same as the calendar year.

Push the input forward by three months by adding 3/12 to the input yearmon object so that October, November and December get pushed into the next calendar year but no other month is and then format:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...