简体   繁体   English

将日历季度转换为财务季度

[英]Transforming Calendar Quarter to Financial Quarter

I am working with a dateframe (INPUT) that contains number the of transaction of a product per calendar quarter. 我正在使用一个日期框架(INPUT),其中包含每个日历季度产品交易的编号。 The first column (DATE) contains the calendar quarter in this format "2016 Q2". 第一列(DATE)包含格式为“ 2016 Q2”的日历季度。 I would like to transform this date into the a financial quarter format such as "2016/17 Q1". 我想将此日期转换为财务季度格式,例如“ 2016/17 Q1”。 The financial year start in the 1st April. 财政年度始于4月1日。

I came up with the following code which does the job, but I was wondering if there is a formula or a neater code that I could use. 我想出了下面的代码来完成这项工作,但是我想知道是否可以使用公式或更整洁的代码。

INPUT$FY_Date=character(nrow(INPUT))

for (i in 1:nrow(INPUT)) {
    INPUT$FY_Date[i]= if(substr(INPUT$DATE[i],7,7)==1)  paste(as.numeric(substr(INPUT$DATE[i],1,4))-1,"/",substr(INPUT$DATE[i],3,4)," Q4",sep="") else 

    paste(substr(INPUT$DATE[i],1,4),"/",  formatC(as.numeric(substr(INPUT$DATE[i],3,4))+1,width=2,format="d",flag=0)," Q",as.numeric(substr(INPUT$DATE[i],7,7))-1,sep="")
}     

I could not find any previous related posts so I would appreciate any guidance. 我以前找不到任何相关的帖子,因此我希望您能提供任何指导。

Using the "yearqtr" class defined in zoo we can do it in two lines of code. 使用zoo中定义的"yearqtr"类,我们可以用两行代码来实现。

Convert to "yearqtr" . 转换为"yearqtr" The "yearqtr" class uses an internal representation of year + (qtr-1)/4 where qtr is 1, 2, 3 or 4 so adding 3/4 will shift it to the year-end year and fiscal quarter. "yearqtr"类使用"yearqtr" year + (qtr-1)/4的内部表示形式,其中qtr是1、2、3或4,因此加3/4会将其移动到年末年份和财政季度。 Then in the final line of code as.integer will extract the year-end year. 然后,在最后一行代码中, as.integer将提取年末年份。 format function can be used to get the rest where %y means 2 digit year and %q means quarter. format函数可用于获取其余值,其中%y表示2位数的年份, %q表示四分之一。

library(zoo)

# test input
yq <- c("2016 Q2", "2016 Q3", "2016 Q4", "2017 Q1")

fyq <- as.yearqtr(yq, format = "%Y Q%q") + 3/4
paste0(as.integer(fyq) - 1, format(fyq, "/%y Q%q"))

giving: 给予:

[1] "2016/17 Q1" "2016/17 Q2" "2016/17 Q3" "2016/17 Q4"

Note that if you don't need the specific format shown in the question you could just use format(fyq) in place of the last line or maybe format(fyq, "%YQ%q") . 请注意,如果您不需要问题中显示的特定格式,则可以仅使用format(fyq)代替最后一行,也可以使用format(fyq, "%YQ%q")

Update: Minor code improvements. 更新:较小的代码改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM