View source: R/50-ordered_sequence-ops.R
| nearest_key | R Documentation |
Returns the existing key closest to query. Generalizes min_key() and
max_key(): it resolves by order alone at the extremes and on an exact hit,
and only needs a distance metric when query falls strictly between two
distinct keys.
nearest_key(x, query, ties = c("lower", "upper", "both"))
x |
An |
query |
Query key. |
ties |
How to resolve an equidistant tie between the two distinct
neighbouring keys (the only case a tie can arise): |
Resolution:
Exact match, or query below/above every key: decided by order alone, so it
works for every key type (including character).
query strictly between two distinct keys: returns the closer of the two by
abs(query - key), with an equidistant tie resolved by ties. This case
needs a numeric difference, so it supports numeric, Date, and POSIXct
keys; for character (and other non-subtractable orderable keys) it errors,
because "closer" is undefined – use lower_bound() / peek_key() for
order-based lookup instead.
Duplicate keys are not disambiguated here: the return is a key value, and
peek_key() / pop_key() select the FIFO-first element for that key.
The nearest key, or NULL when x is empty. A length-1 key except
with ties = "both" on an exact tie, which returns both equidistant keys.
Feed the result to peek_key() / pop_key() to read or remove the matching
element.
lower_bound(), peek_key(), min_key(), max_key(), key_at()
x <- ordered_sequence("a", "b", "c", "d", keys = c(1, 2, 4, 8))
nearest_key(x, 3) # 2 and 4 are equidistant -> lower key (2)
nearest_key(x, 3, ties = "upper") # 4
nearest_key(x, 3, ties = "both") # c(2, 4)
nearest_key(x, 5) # 4
nearest_key(x, 100) # 8 (above all)
nearest_key(ordered_sequence()) # NULL
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.