View source: R/chronon_traverse.R
| chronon_traverse | R Documentation |
Walks out from a chronon through the time units it is related to by
chronon_cardinality() methods, either to coarser or finer time units,
accumulating a value along the way. This is a low-level building block for
questions about how time units relate, such as "which coarser time units
does a month nest within a fixed number of times?" or "which finer time
units divide a day between 3 and 15 times?".
chronon_traverse(
x,
.f,
.init,
.until = function(acc, granule) FALSE,
direction = c("coarser", "finer"),
graph = c("fixed", "cardinality")
)
x |
A time granule to start from (e.g. |
.f |
A function |
.init |
The accumulated value at |
.until |
A function |
direction |
Walk to |
graph |
Which relationships to walk along: |
The traversal is breadth-first, and when a time unit can be reached along several paths only the first (shortest) is followed. The accumulated value is a fold along that path, which suits values that compose along a path, such as fixed cardinalities, the path itself, or its length.
Context-dependent cardinalities don't compose along a path: the 29 days of
February 2024 times the 3 months of a quarter is not the 91 days of the
first quarter of 2024. Compute these from x itself, for example with
function(acc, from, to) chronon_cardinality(x, to, at = at).
A list with one element for each time unit reached (excluding x's
own time unit), named by its class and in breadth-first order. Each element
is a list of granule, a single unit (n = 1L) granule of that time unit
which inherits the calendar and properties (such as time zone) of x, and
value, the accumulated value. A time unit with no registered
relationships gives an empty list.
# Cumulative fixed cardinality of each coarser time unit
card_up <- function(acc, from, to) acc * chronon_cardinality_fixed(from, to)
# There are 3 months in a quarter, and 12 in a year
traversal <- chronon_traverse(cal_gregorian$month(1L), card_up, 1)
vapply(traversal, function(e) e$value, numeric(1L))
# Coarser time units containing at most 15 hours
traversal <- chronon_traverse(
cal_gregorian$hour(1L), card_up, 1,
.until = function(acc, granule) acc >= 15
)
vapply(traversal, function(e) e$value, numeric(1L))
# Finer time units that divide a day up to 15 times
card_down <- function(acc, from, to) acc * chronon_cardinality_fixed(to, from)
traversal <- chronon_traverse(
cal_gregorian$day(1L), card_down, 1,
.until = function(acc, granule) acc > 15,
direction = "finer"
)
vapply(traversal, function(e) e$value, numeric(1L))
# The path from minutes to each coarser time unit
traversal <- chronon_traverse(
cal_gregorian$minute(1L),
function(acc, from, to) c(acc, class(to)[[1L]]),
.init = "mixtime::tu_minute"
)
vapply(traversal, function(e) paste(e$value, collapse = " > "), character(1L))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.