Closest.Rd
Find the closest value(s) of a number in a vector x. Multiple values will be reported, if the differences are the same or if there are duplicates of the same value.
Closest(x, a, which = FALSE, na.rm = FALSE)
the value or index in x which is closest to a
# basic
set.seed(8)
x <- runif(10) * 10
Closest(x, 3.1)
#> [1] 3.215092
sort(x)
#> [1] 2.078233 2.908734 3.215092 4.662952 6.444911 6.518713 7.189275 7.691470
#> [9] 7.996580 9.322698
y <- sample(10, size=10, replace=TRUE)
# multiple observations of the same closest value
Closest(y, a=6)
#> [1] 6 6
# get the relevant positions
Closest(y, a=6, which=TRUE)
#> [1] 5 6
# two different values having the same distance
Closest(c(2, 3, 4, 5), a=3.5)
#> [1] 3 4
# vectorize "a"
Closest(c(2, 3, 4, 5), a=c(3.1, 3.9))
#> [[1]]
#> [1] 3
#>
#> [[2]]
#> [1] 4
#>
# vectorize "which"
Closest(c(2, 3, 4, 5), a=3.1, which=c(FALSE, TRUE))
#> [[1]]
#> [1] 3
#>
#> [[2]]
#> [1] 2
#>
# vectorize both
Closest(c(2, 3, 4, 5), a=c(3.1, 3.9), which=c(FALSE, TRUE))
#> [[1]]
#> [1] 3
#>
#> [[2]]
#> [1] 3
#>