Linear-cyclic granularity combinations are produced by combining two granularities, one nested within the other. For example, the year and the month, or the week and the day-of-week. It is assumed that the first granularity is linear (i.e., it increases over time), and the second granularity is cyclic, and nested within the first granularity. The second granularity may be strictly periodic (e.g., month-of-year or day-of-week), quasi-periodic (e.g., day-of-month or day-of-year), or aperiodic (e.g., public holidays).
Arguments
- gran_fun1
A function that extracts a linear granularity from a date. This function must return an integer.
- gran_fun2
A function that extracts a cyclic granularity from a date, that is nested within the linear granularity returned by
gran_fun1
. This function must return an integer.- gran_levels
A character vector of the granularity levels for
gran_fun2
.- gran_name
A character string giving the name of the linear granularity.
- periodic
A logical value indicating if the second (cyclic) granularity is strictly periodic.
Examples
# Year-quarter granularity
## Compute quarter from a Gregorian date
quarter <- function(date) {
ceiling(month_of_year(date) / 3)
}
year_quarter <- linear_cyclic(year, quarter, paste0("Q", 1:4), "year-quarter")
year_quarter(gregorian_date(2025, 6, 25) + 1:10)
#> <year-quarter[10]>
#> [1] 2025-Q2 2025-Q2 2025-Q2 2025-Q2 2025-Q2 2025-Q3 2025-Q3 2025-Q3 2025-Q3
#> [10] 2025-Q3
# Week-day granularity
## Compute week as linear granularity
week <- function(date) {
(seq_along(date) - 1) %/% 7 + 1
}
## Compute day as numerical cyclic granularity
day <- function(date) {
day_of_week(date, numeric = TRUE)
}
week_day <- linear_cyclic(
week,
day,
c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
gran_name = "week-day"
)
week_day(gregorian_date(2025, 6, 25) + 1:10)
#> <week-day[10]>
#> [1] 1-Thursday 1-Friday 1-Saturday 1-Sunday 1-Monday 1-Tuesday
#> [7] 1-Wednesday 2-Thursday 2-Friday 2-Saturday