Tie breaker in function "match"

Viewed 135

I have a list as follows:

rn<-c(10,20,20,10,50,80,100)
rn
#[1]  10  20  20  10  50  80 100

I have another list say q, which is a sorted version of rn in ascending order. I want to find the index of the numbers in q in my original list rn.

So, I am using match:

q<-sort(rn)
match(q,rn)
#[1] 1 1 2 2 5 6 7

So, match behaves as expected and returns the first index for each number being searched for. Thus, even though 10 appears in index 1 and 4 in rn, match only gets the first one and returns 1 for both searches.

Is there a function in R (or any package), that acts like match, but that can handle ties? It should be fine if the tie is broken at random.

1 Answers

When q is rn sorted in ascending order, you might be able to use order

order(rn)
#[1] 1 4 2 3 5 6 7

In other cases, you could convert the vectors to character and use make.unique to account for repeated values

match(make.unique(as.character(q)), make.unique(as.character(rn)))
#[1] 1 4 2 3 5 6 7
Related