0

Building on R - Fastest way to find nearest value in vector, I am interested in getting the nearest value in a vector prior to a specific value.

The DescTools package Closest does not differentiate according to direction.

Eg.

x=c(1,7:10)
min(DescTools::Closest(x, 6, which = F, na.rm = FALSE))        

would return 7, while I want 1. Anyone?

epiNS
  • 353
  • 2
  • 7

1 Answers1

2

You could try writing a simple function to do this.

closest_preceding <- function(vec, value) max(vec[vec < value])

closest_preceding(x, 6)
#> [1] 1
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87