Abir Majumdar
Abir Majumdar

Reputation: 83

R: Matching components of vectors within range of each other

I have two distinct vectors from which I've indexed every possible combination of perfect matches:

starts <- c(54, 54, 18, 20, 22, 22, 33, 33, 33, 37, 42, 44, 44, 51, 11, 17, 19, 19, 19, 19, 22, 23, 23, 24, 24)
ends <- c(22, 14, 14, 14, 14, 14, 14, 14, 14, 24, 24, 25, 25, 25, 25, 26, 26, 29, 30, 31, 32, 33, 33, 33, 33)

which(outer(starts, ends, "=="), arr.ind=TRUE)

Now, instead of trying to find exact matches, I'd like to find combinations of components that fall within a certain range of each other: say +/- 5. I've made a range (-5:5) and tried introducing it as a function in place of "==", but it hasn't really worked out.

Thank you very much.

Upvotes: 2

Views: 168

Answers (1)

Andrie
Andrie

Reputation: 179428

You can do this by writing a small helper function that does the comparison:

cmp <- function(x, y, cutoff=5){abs(x-y) <= cutoff}

which(outer(starts, ends, cmp), arr.ind=TRUE)

       row col
  [1,]   3   1
  [2,]   4   1
  [3,]   5   1
  [4,]   6   1
  [5,]  16   1
  [6,]  17   1
  [7,]  18   1
       ... etc.

Upvotes: 2

Related Questions