【问题标题】:How to find matches among two list of names如何在两个名称列表中查找匹配项
【发布时间】:2013-08-12 03:37:54
【问题描述】:

我有两个长的名字向量(list.1list.2)。我想运行一个循环来检查 list.2 中的任何名称是否与 list.1 中的任何名称匹配。如果确实如此,我想将匹配名称在向量 list.1 中的位置值附加到向量 result

 for (i in list.2){
  for (j in list.1){
    if(length(grep(list.2[i], list.1[j]), ignore.case=TRUE)==0){
      append(result, j)
      break
    } else append(nameComment.corresponding, 0)
  }
}

上面的代码真的很暴力,因为我的向量有 5,000 和 60,000 个名字长,它可能会运行超过 360,000,000 次循环。我该如何改进它?

【问题讨论】:

  • 你看过%in%match()吗?
  • 下面的建议有用吗?如果某个答案确实解决了您的问题,您可能需要考虑投票和/或将其标记为已接受,以表明问题已得到回答,方法是勾选合适答案旁边的绿色小复选标记。您没有义务这样做,但它有助于保持网站没有未回答的问题,并奖励那些花时间解决您的问题的人。
  • 这完全是集合操作intersect 的用途......在你的情况下用match(intersect(list.1, list.2), list.1) 包装它。永远不要写 O(N1*N2) 循环......

标签: r list intersection intersect


【解决方案1】:

which%in% 可能适合此任务,或者 match 取决于您的目标。需要注意的一点是match 在它的第二个参数中返回第一个参数的 first 匹配的索引(也就是说,如果您在查找表中有多个值,则只有第一个匹配将被退回):

set.seed(123)
#  I am assuming these are the values you want to check if they are in the lookup 'table'
list2 <- sample( letters[1:10] , 10 , repl = T )
[1] "c" "h" "e" "i" "j" "a" "f" "i" "f" "e"

#  I am assuming this is the lookup table
list1 <- letters[1:3]
[1] "a" "b" "c"

#  Find which position in the lookup table each value is, NA if no match
match(list2 , list1 )
[1]  3 NA NA NA NA  1 NA NA NA NA

【讨论】:

  • +1。为了完整起见,还有match(y, x)(工作方式略有不同)和which(is.element(x, y))(其中is.element%in% 相同,但可能更...直观?...给新用户,因为函数名称比%in%更具描述性)。
  • @AnandaMahto 谢谢。这实际上是一个可怕的例子(恕我直言!)但当时我的小男孩在纠缠我!我会稍微重新调整一下
【解决方案2】:

这完全是集合操作intersect/union/setdiff() 的用途:

list.1 = c('Alan','Bill','Ted','Alice','Carol')
list.2 = c('Carol','Ted')
intersect(list.1, list.2)
 "Ted" "Carol"

...或者如果您真的希望索引进入 list.1:

match(intersect(list.1, list.2), list.1)
  3 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    相关资源
    最近更新 更多