This function takes an ordered vector of numeric or character values and finds the pair that bracket a third value, x
. If x
is exactly equal to one of the values in the vector, then a single value equal to x
is returned. If x
falls outside of the range of the vector, then the least/most extreme value of the vector is returned (depending on which side of the distribution of the vector x
resides). Optionally, users can have the function return the index of the values that bracket x
.
Arguments
- x
A numeric or character vector.
- by
A numeric or character vector. These should be sorted (from high to low or low to high... if not, an error will result).
- index
Logical. If
FALSE
(default), then numeric values inby
will be returned. IfTRUE
, then the index or indices of the bracketing value(s) will be returned.- inner
Logical. If
TRUE
(default), then ifx
is surrounded by at least one series of repeating values, return the values (or indices) among the repeated sequence(s) closest to the value ofx
. IfFALSE
, return the value(s) (or indices) among the repeated sequence(s) farthest from the value ofx
. For example, ifindex = TRUE
,by = c(1, 2, 2, 2, 3, 3)
, andx = 2.5
, settinginner = TRUE
will return the index of the third 2 and first 3. Ifinner = FALSE
, then the function returns the index of the first 2 and second 3.- warn
Logical. If
TRUE
, then warn ifx
is outside the range ofby
.
Value
If x
is a single value, then the function will return a numeric vector of length 1 or 2, depending on how many values bracket x
. If all values of by
are the same, then the median index (or value) of by
is returned. If x
is a vector, then the result will be a list with one element per item in x
with each element having the same format as the case when x
is a single value.
Examples
by <- 2 * (1:5)
bracket(4.2, by)
#> [1] 4 6
bracket(6.8, by)
#> [1] 6 8
bracket(3.2, by, index=TRUE)
#> [1] 1 2
bracket(c(3.2, 9.8, 4), by)
#> [[1]]
#> [1] 2 4
#>
#> [[2]]
#> [1] 8 10
#>
#> [[3]]
#> [1] 4
#>
bracket(2, c(0, 1, 1, 1, 3, 5), index=TRUE)
#> [1] 4 5
bracket(3, c(1, 2, 10))
#> [1] 2 10
bracket(2.5, c(1, 2, 2, 2, 3, 3), index=TRUE)
#> [1] 4 5
bracket(2.5, c(1, 2, 2, 2, 3, 3), index=TRUE, inner=FALSE)
#> [1] 2 6
bracket(2.9, c(1, 2, 2, 2, 3, 3), index=TRUE)
#> [1] 4 5
bracket(2.9, c(1, 2, 2, 2, 3, 3), index=TRUE, inner=FALSE)
#> [1] 2 6
# \donttest{
by <- 1:10
bracket(-100, by)
#> [1] 1
bracket(100, by)
#> [1] 10
# }