Dnaiel
Dnaiel

Reputation: 7832

Obtain the indexes of one vector into another vector but keeping the order

Let us say I have two vectors a, and b,

a = c(1,21,3,42,5,6,7,8,9)
b = c(2,5,7,10,3,40,1,21,42,6,8,9)

If I do:

which(b %in% a)

I obtain,

 2  3  5  7  8  9 10 11 12

But I'd like to keep the order in which they appear, i.e., I'd like to have as the output,

7 8 5 9 2 10 3 11 12

since 1 is in position 7 in b, 21 is in position 8 in b, etc.

Is that easy to do?

Upvotes: 1

Views: 48

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

Perhaps you can try match instead, but note that match and %in% don't do exactly the same thing:

> match(a, b)
[1]  7  8  5  9  2 10  3 11 12

Upvotes: 2

Related Questions