For each value in a numeric vector, return the closest match from a vector of candidate values.

snap(x, rule = 1, left = TRUE, ...)

Arguments

x

A numeric vector

rule

a vector of (finite numeric) candidates, or a single value giving candidate interval on the real number line

left

whether to return the lesser of two equidistant candidates

...

ignored

Details

If rule is scalar, it must be positive; a rule will be constructed as a sequence of rule-spaced values that includes zero and includes values at least as extreme as the extremes of x. In some sense, this function is the complement to cut: whereas in cut one specifies the "breaks", with snap one specifies a set of "attractors" (breaks are the implied midpoints); both functions map their primary argument to a (possibly) smaller set of values.

Note

If length of x is zero, it is returned unmodified. If length of rule is zero, value is all NA.

Author

Tim Bergsma

Examples

snap(c(0.0, 1.0, 1.2, 2.0, 2.9, 3))
#> [1] 0 1 1 2 3 3

snap(-3:3, 0.3)
#> [1] -3.0 -2.1 -0.9  0.0  0.9  2.1  3.0

snap(c(3,NA,5), c(2,3,6))
#> [1]  3 NA  6

snap(c(3,NA,5), numeric(0))
#> [1] NA NA NA