R:检查向量中的字符串是否存在于其他向量中,并返回匹配项的名称



我需要比%in%match()更具选择性的工具。我需要一段代码,将字符串向量与另一个向量匹配,并返回匹配项的名称。

目前我有以下内容,

test <- c("country_A", "country_B", "country_C", "country_D", "country_E", "country_F") rating_3 <-  c("country_B", "country_D", "country_G", "country_K")
rating_3 <-  c("country_B", "country_D", "country_G", "country_K")
rating_4 <- c("country_C", "country_E", "country_M", "country_F)

i <- 1
while (i <= 33) {
  print(i)
  print(test[[i]])
  if (grepl(test[[i]], rating_3) == TRUE) {
    print(grepl(test[[i]], rating_3)) }
  i <- i+1
},

这应该检查rating_3中存在的test的每个元素,但由于某种原因,它只返回位置、字符串名称和警告;

 [1]
 [country_A]
 There were 6 warnings (use warnings() to see them)

我需要知道这段代码失败了什么,但我希望最终让它仅在另一个向量内时才返回名称,如果可能的话,一次针对多个向量进行测试,让它打印它适合的向量的名称,类似于

[1]
[String]
[rating_3]

我怎么能得到这样的东西?

如果没有可重现的示例,很难确定您到底需要什么,但我认为这可以使用%in%来完成:

# create reprex
test <- sample(letters,10)
rating_3 <- sample(letters, 20)
print(rating_3[rating_3 %in% test])  
[1] "r" "z" "l" "e" "m" "c" "p" "t" "f" "x" "n" "h" "b" "o" "s" "v" "k" "w" "a"
[20] "i"

最新更新