Epimetheus
Epimetheus

Reputation: 1147

index vector by value in R

Say I have two character vectors

vec <- c('A', 'B', 'C', 'D', 'E') 
pat <- c('D', 'B', 'A')

how do I get the indexes of the occurrences in vec of the values in pat in the order they appear in pat?

I can try

which(vec %in% pat)

but this gives me them in the incorrect order: 1 2 4. I want them as 4 2 1.

Upvotes: 1

Views: 96

Answers (1)

loki
loki

Reputation: 10350

I tried different ways to solve this problem before and always found that the easiest way to solve it is the solution as mentioned in @DavidArenburg's comment:

match(pat, vec)
# [1] 4 2 1

Upvotes: 1

Related Questions