Get index of element in vector with value closest to a target

closest_to_target(vector, target)

Arguments

vector

Identify element in this numeric vector

target

numeric target

Value

an integer indexing vector

Examples

closest_to_target(c(0.1, 0.2, 0.3), 0.05) # 1
#> [1] 1
closest_to_target(c(0.1, 0.2, 0.3), 0.22) # 2
#> [1] 2
closest_to_target(c(0.1, 0.2, 0.3), -0.05) # 1
#> [1] 1
closest_to_target(c(0.1, 0.2, 0.3), 8) # 3
#> [1] 3