Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:检查向量中的字符串是否存在于其他向量中,并返回匹配的名称_R_String_Vector_Matching - Fatal编程技术网

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

R:检查向量中的字符串是否存在于其他向量中,并返回匹配的名称,r,string,vector,matching,R,String,Vector,Matching,我需要一个比%中的%或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("

我需要一个比%中的
%或
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
},
我需要知道这段代码失败了什么,但我希望最终它只在另一个向量中返回名称,如果可能的话,一次对多个向量进行测试,让它打印出适合它的向量的名称,比如

[1]
[String]
[rating_3]

我怎么能得到那样的东西

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

# 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"
#创建reprex

如果您提供了一个示例输入数据,那么测试将更容易帮助您,这样我们就可以实际运行和测试代码。这是朝着正确方向迈出的一步,而且比我使用的要简单得多,我只需修复
打印(rating_3[rating_3%in%test])
,它就可以正常工作了。我将尝试使用一个函数,让它在rating_4和rating_5.oops上迭代。我的打字错误。现在答案中编辑了它。如果答案对你有效,请随意接受!
# 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"