'Sorting out irregular quarters (starting in July) using Tidyverse and Lubridate
I am currently trying to generate (mutate) two columns:
- "NewThisYear" for observations that occurred in the current financial year
- "NewThisQuarter" for observations that occurred this current quarter
My usual approach involves the code attached. This code has worked for when the financial year starts in January but I can't figure out what would be a good approach to extract the following year (i.e 2022) for the first two quarters of the year that start in 2021. Would the best way to tackle this be to add + 1 to the year if the Quarter is 1|2 or is there a simpler way to achieve this?
Thanks for the pointers!
Code:
Calendar <- structure(list(Date = structure(c(18780, 18787, 18794, 18801,
18808, 18815, 18822, 18829, 18836, 18843, 18850, 18857, 18864,
18871, 18878, 18885, 18892, 18899, 18906, 18913, 18920, 18927,
18934, 18941, 18948, 18955, 18962, 18969, 18976, 18983, 18990,
18997, 19004, 19011, 19018, 19025, 19032), class = "Date"), NameMonthShort = structure(c(6L,
6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L,
9L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L,
12L, 1L, 1L, 1L, 1L, 2L, 2L), .Label = c("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
), class = c("ordered", "factor")), Year = c(2021, 2021, 2021,
2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021,
2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021,
2021, 2021, 2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022, 2022,
2022), Quarter = c(4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), QuarterYear = c("4-2021",
"4-2021", "4-2021", "4-2021", "4-2021", "1-2021", "1-2021", "1-2021",
"1-2021", "1-2021", "1-2021", "1-2021", "1-2021", "1-2021", "1-2021",
"1-2021", "1-2021", "1-2021", "2-2021", "2-2021", "2-2021", "2-2021",
"2-2021", "2-2021", "2-2021", "2-2021", "2-2021", "2-2021", "2-2021",
"2-2021", "2-2021", "3-2022", "3-2022", "3-2022", "3-2022", "3-2022",
"3-2022")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-37L))
Calendar <- Calendar %>%
mutate(
NewThisYear = case_when(
Year == year(Sys.Date()) ~ "Yes",
TRUE ~ as.character("No")
),
NewThisQuarter = case_when(
Year == year(Sys.Date()) & Quarter == quarter(Sys.Date(), with_year = F, fiscal_start = 7) ~ "Yes",
TRUE ~ as.character("No")
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
