Search code examples
rvectormaxmin

closest smaller and bigger value comparing two vectors


Let´s say I have two vectors

a <- c(5,10,12)
b <- c(4,11,15)

I would like to compare a with b and obtain the smaller closest value to each element. The smaller closest value to 5 is 4, for 10 is 4 and for 12 is 11. And the same but finding the closest bigger value. For 5 is 11, for 10 is 11 and for 12 is 15.

Desired vector of closest smaller values:

         4 4 11

Desired vector of closest bigger values:

        11 11 15

I found another example using the function closest from the package DescTools, but the results are different

      > unlist(lapply(a, function(i) min(Closest(x = b, a = i))))
      [1]  4 11 11
      > unlist(lapply(a, function(i) max(Closest(x = b, a = i))))
      [1]  4 11 11

Do you know how I could achieve my objective?


Solution

  • This should do it:

    > sapply(a,function(x) b[tail(which(b<x),1)])
    [1]  4  4 11
    > sapply(a,function(x) b[head(which(b>x),1)])
    [1] 11 11 15