将一个列表中的项目替换为另一个列表中的匹配名称

时间:2018-03-08 19:53:50

标签: r indexing lookup-tables

我觉得我已经忘记了一些非常明显的事情......

我们假设我们有两个列表ab,其长度不同:

a <- list(me = "you1", they = "our1", our = "till1", grow = "NOPE1")
b <- list(me = "my2", their = "his2", our = "aft2", new = "noise2", 
          they = "now2", b_names = "thurs2")

我们希望将a中的项目替换为b中的相应项目,如果 b中的项目与a中的项目具有相同的名称{1}}。

手动,基本上这等同于从列表me, our, they中的那些项替换列表a中的b

对于我的生活,我想出的唯一方法是使用Reduce而不是match%chin%等来查找intersect离子的名称,然后始终使用最后一个列表对象作为查找表。我认为你真的不需要Reduce,因为intersect可以找到它自己的......但无论如何......

我是否只是忘记了一种更简单,更直接的方式?

这是我的代码..它有效......但这不是重点。

reduce.names <- function(...){
    vars <- list(...)
    if(length(vars) > 2){
        return("only 2 lists allowed...")
    }else {
        Reduce(intersect, Map(names,vars))
    }
}

> matched_names <- reduce.names(a,b)
> matched_names
[1] "me"   "they" "our" 

a[matched_names] <- b[matched_names]
> a
 $me
 [1] "my2"

 $they
 [1] "now2"

 $our
 [1] "aft2"

 $grow
 [1] "NOPE1"
这是另一种有效的方法......但似乎多余且粗略......
> merge(a,b) %>% .[names(a)]
$me
[1] "my2"

$they
[1] "now2"

$our
[1] "aft2"

$grow
[1] "NOPE1"

我非常感谢任何建议/替代方法/提醒我已完全忘记的某些base功能。感谢。

0 个答案:

没有答案
相关问题