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.
Usage
nearest_key(x, query, ties = c("lower", "upper", "both"))Value
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.
Details
Resolution:
Exact match, or
querybelow/above every key: decided by order alone, so it works for every key type (includingcharacter).querystrictly between two distinct keys: returns the closer of the two byabs(query - key), with an equidistant tie resolved byties. This case needs a numeric difference, so it supportsnumeric,Date, andPOSIXctkeys; forcharacter(and other non-subtractable orderable keys) it errors, because "closer" is undefined – uselower_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.
Examples
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)
#> [1] 2
nearest_key(x, 3, ties = "upper") # 4
#> [1] 4
nearest_key(x, 3, ties = "both") # c(2, 4)
#> [1] 2 4
nearest_key(x, 5) # 4
#> [1] 4
nearest_key(x, 100) # 8 (above all)
#> [1] 8
nearest_key(ordered_sequence()) # NULL
#> NULL
