Search code examples
rvectorcomparecriteria

Comparing each value in a vector to all other values based on criteria


I have a vector of unique values, but I want to get only the ones meeting a specific criteria with at least one other value. For example, if I have a vector like this one

v <- c(1,2,5,6,8,10,15,16)

And the criteria I want to meet is all values that have at least one other value in the vector with a difference of 1 between them, the result will be

1,2,5,6,15,16

I want to be able to do it with different functions. So for this example let's assume I use a function that gives me the absolute difference between two given number:

AbsDiff <- function(x,y){
           abs(x-y)
           }

So the solution should run the AbsDiff function for each value against all other values, and get the desired result.


Solution

  • Here's a slightly modified version of your function:

    m <- outer(v, v, FUN = function(x,y) abs(x-y) == 1)
    v[colSums(m) > 0]
    # [1]  1  2  5  6 15 16
    

    As you can see, I added a logical check to your function that is TRUE whenever the absolute difference between two values is exactly 1. That makes it easier to extract the relevant indices afterwards.


    If you want to use your function as it is now, you could do it like so:

    m <- outer(v, v, FUN = AbsDiff)
    v[colSums(m == 1) > 0]
    

    That means we do the check for ==1 in the second step.