bracket: Identify values bracketing another value

View source: R/bracket.r

bracketR Documentation

Identify values bracketing another value

Description

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.

Usage

bracket(x, by, index = FALSE, inner = TRUE, warn = FALSE)

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 in by will be returned. If TRUE, then the index or indices of the bracketing value(s) will be returned.

inner

Logical. If TRUE (default), then if x is surrounded by at least one series of repeating values, return the values (or indices) among the repeated sequence(s) closest to the value of x. If FALSE, return the value(s) (or indices) among the repeated sequence(s) farthest from the value of x. For example, if index = TRUE, by = c(1, 2, 2, 2, 3, 3), and x = 2.5, setting inner = TRUE will return the index of the third 2 and first 3. If inner = FALSE, then the function returns the index of the first 2 and second 3.

warn

Logical. If TRUE, then warn if x is outside the range of by.

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)
bracket(6.8, by)

bracket(3.2, by, index=TRUE)
bracket(c(3.2, 9.8, 4), by)

bracket(2, c(0, 1, 1, 1, 3, 5), index=TRUE)
bracket(3, c(1, 2, 10))

bracket(2.5, c(1, 2, 2, 2, 3, 3), index=TRUE)
bracket(2.5, c(1, 2, 2, 2, 3, 3), index=TRUE, inner=FALSE)
bracket(2.9, c(1, 2, 2, 2, 3, 3), index=TRUE)
bracket(2.9, c(1, 2, 2, 2, 3, 3), index=TRUE, inner=FALSE)


by <- 1:10
bracket(-100, by)
bracket(100, by)



omnibus documentation built on Sept. 17, 2024, 5:09 p.m.