我有一个大型数据库 (POY),其中包含 2011 年至 2017 年的数据,其中包含一个日期列。我需要做两件事:使按季度和按财政年度拆分成为可能。
不幸的是,我们的财政年度与日历年不同,而是从 7 月到 6 月。这也意味着我的第 1 季度从 7 月持续到 9 月。
我写了一些似乎工作正常但似乎相当冗长的代码(尤其是第二部分)。有没有人对这个初学者有任何建议以使其更有效率?
#Copy of date column and splitting it in 3 columns for year, month and day
library(tidyr)
POY$Date2 <- POY$Date
POY<-separate(POY, Date2, c("year","month","day"), sep = "-", convert=TRUE)
#Making a quarter variable
POY$quarter[POY$month<=3] <- "Q3"
POY$quarter[POY$month>3 & POY$month <=6] <- "Q4"
POY$quarter[POY$month>6 & POY$month <=9] <- "Q1"
POY$quarter[POY$month>9 & POY$month <=12] <- "Q2"
POY$quarter <- as.factor(POY$quarter)
Run Code Online (Sandbox Code Playgroud)
对于 Fiscal Year 变量:它运行 7 - 6 月,所以: …