我尝试根据元素github
将元素listA
从listB
附加到id
。我怎样才能做到这一点?
G1 <- list(id = "aaa", github = "www.github.aaa")
G2 <- list(id = "bbb", github = "www.github.bbb")
R1 <- list(id = "aaa", reddit = "www.reddit.aaa")
R2 <- list(id = "bbb", reddit = "www.reddit.bbb")
listA <- list(G1, G2)
listB <- list(R2, R1)
使用:
> listB
[[1]]
[[1]]$id
[1] "bbb"
[[1]]$reddit
[1] "www.reddit.bbb"
[[2]]
[[2]]$id
[1] "aaa"
[[2]]$reddit
[1] "www.reddit.aaa"
我要做的是:
> listB
[[1]]
[[1]]$id
[1] "bbb"
[[1]]$reddit
[1] "www.reddit.bbb"
[[1]]$github
[1] "www.github.bbb"
[[2]]
[[2]]$id
[1] "aaa"
[[2]]$reddit
[1] "www.reddit.aaa"
[[1]]$github
[1] "www.github.aaa"
我尝试mapply
,但它没有给我预期的结果。相反,它跨越两个列表:
> mapply(c, listA, listB, SIMPLIFY=FALSE)
[[1]]
[[1]]$id
[1] "aaa"
[[1]]$github
[1] "www.github.aaa"
[[1]]$id
[1] "bbb"
[[1]]$reddit
[1] "www.reddit.bbb"
[[2]]
[[2]]$id
[1] "bbb"
[[2]]$github
[1] "www.github.bbb"
[[2]]$id
[1] "aaa"
[[2]]$reddit
[1] "www.reddit.aaa"
谢谢
答案 0 :(得分:1)
一种可能性是将它们转换为data.frames并执行merge
:
merge(do.call(rbind, lapply(listA, data.frame, stringsAsFactors=FALSE)),
do.call(rbind, lapply(listB, data.frame, stringsAsFactors=FALSE)), by="id")
返回
id github reddit
1 aaa www.github.aaa www.reddit.aaa
2 bbb www.github.bbb www.reddit.bbb