我觉得我已经忘记了一些非常明显的事情......
我们假设我们有两个列表a
和b
,其长度不同:
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
功能。感谢。