R矢量与有序索引匹配

rmf*_*rmf 6 r

这里我有两个字符串向量,其顺序很重要,无法更改.

vec1 <- c("carrot","carrot","carrot","apple","apple","mango","mango","cherry","cherry")
vec2 <- c("cherry","apple")
Run Code Online (Sandbox Code Playgroud)

我想知道vec2中的元素是否出现在vec1中,如果是,则在哪里(索引/位置)以及以什么顺序出现.

我试过which(vec1 %in% vec2)4 5 8 9.这些是正确的索引,但顺序错误.我试过match(vec2,vec1)8 4.仅返回第一个匹配项.如果vec1是唯一的,这将有效.

理想情况下,我正在寻找这个结果:8 9 4 5.樱桃首先在8号和9号匹配,然后苹果在4号和5号匹配.

有没有一种聪明的方法来做到这一点,而不诉诸循环?

Mam*_*zal 11

你可以试试这个

unlist(lapply(vec2, function(x) which(vec1 %in% x)))
[1] 8 9 4 5
Run Code Online (Sandbox Code Playgroud)

这将连续返回vec2中存在的vec1中的元素.