rmf rmf - 23 days ago 6
R Question

R vector-vector matching with ordered indices

Here I have two string vectors whose order is important and cannot be changed.

vec1 <- c("carrot","carrot","carrot","apple","apple","mango","mango","cherry","cherry")
vec2 <- c("cherry","apple")


I wish to find out if elements in vec2 appears in vec1 and if so, where (index/position) and in what order.

I tried
which(vec1 %in% vec2)
which gives
4 5 8 9
. These are correct indices, but in the wrong order. I tried
match(vec2,vec1)
which gives
8 4
. Only the first match is returned. This would work if vec1 was unique.

Ideally, I am looking for this result:
8 9 4 5
.
cherry is first matched at pos 8 and 9 and then apple is matched at 4 and 5.

Is there a smart way to do this without resorting to loops?

Answer

you can try this

unlist(lapply(vec2, function(x) which(vec1 %in% x)))
[1] 8 9 4 5

which will return successively the elements in vec1 present in vec2 one by one.