r - Index of vector elements according to another vector

Viewed 40

Assume two character, A and B:

A <- c("A", "B", "B", NA, "D2", "K")
B <- c("A", "B", "C", "D1", "D2", "E", "F", "K", "L")

While B only contains unique entries, elements in A don't have to be unique.

Now I'd like to get the indices of the elements in A as they appear in B, except for NAs. Thus, in the example above, R function should return

1 2 2 5 8

Thanks a lot in advance!

2 Answers

We can use match

c(na.omit(match(A, B)))
#[1] 1 2 2 5 8

Here is another base R option using named vector

> na.omit(setNames(seq_along(B), B)[A])
 A  B  B D2  K
 1  2  2  5  8
attr(,"na.action")
<NA>
   4
attr(,"class")
[1] "omit"
Related