rmf - 9 months ago 41

R Question

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)`

`4 5 8 9`

`match(vec2,vec1)`

`8 4`

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 Source

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.