R:将两个向量的未知匹配次数的索引保存到第三个向量中

R: save indices of unknown number of matches of two vectors into a third

我正在寻找一种方法来将两个向量的未知数量匹配项的索引保存到第三个向量中。例如这里出现问题:

#创建大量字母:

alphabet_soup<-rep(letters[1:10],times=50)

#sample to mix up letters:

alphabet_soup<-sample(alphabet_soup,size=100)

#vector to match
test_vector<-c("a","b","c")

换句话说:alphabeth_soup中“a”、“b”和“c”的匹配索引是什么?

由于每个“a”、“b”和“c”可能有超过 1 个匹配项,r 函数 match()%in% 不起作用。

因为我在 test_vector 之前不知道,或者更确切地说,在我的示例中不是 simple/short,以下解决方案也不可行:

as<-which(alphabet_soup==test_vector[1])
bs<-which(alphabet_soup==test_vector[2])
cs<-which(alphabet_soup==test_vector[3])
matches<-c(as,bs,cs)

循环可能有解决方案,但到目前为止我的尝试失败了。

我认为在 loop/function 中执行此操作是最受控制的方法,但也有使用“grep”的选项。

首先使用 loop/function(我喜欢使用函数,因为它们通常更快更容易构造输出,但原理是相同的)。我已将输出结构化为数据框,以了解数据的来源,但这应该很容易更改

alphabet_soup<-rep(letters[1:10],times=50)
alphabet_soup<-sample(alphabet_soup,size=100)

test_vector<-c("a","b","c")

fun <- function(i) {
  
  matches <- which(alphabet_soup==test_vector[i])
  
  result <- data.frame(vector = test_vector[i], match = matches)
}
dat<-do.call("rbind", lapply(1:length(test_vector), fun))

第二个选项是“grep”,请注意它的输出会自动按字母顺序排序,我不知道如何避免这种情况,另一方面它要简单得多。

grep("a|b|c", alphabet_soup, value = F)