Florent
Florent

Reputation: 1928

Append element of two nested lists with separate order in R

I try to append the element github from the listA to listB based on the element id. How can I achieve this ?

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)

With :

> listB
[[1]]
[[1]]$id
[1] "bbb"

[[1]]$reddit
[1] "www.reddit.bbb"


[[2]]
[[2]]$id
[1] "aaa"

[[2]]$reddit
[1] "www.reddit.aaa"

What I'm trying to do is :

> 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"

I try with mapply but it doesn't give me the expected result. Instead it cross the two list:

> 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"

Thank you

Upvotes: 0

Views: 41

Answers (1)

lmo
lmo

Reputation: 38510

One possibility is to convert them to data.frames and perform a merge:

merge(do.call(rbind, lapply(listA, data.frame, stringsAsFactors=FALSE)),
      do.call(rbind, lapply(listB, data.frame, stringsAsFactors=FALSE)), by="id")

this returns

   id         github         reddit
1 aaa www.github.aaa www.reddit.aaa
2 bbb www.github.bbb www.reddit.bbb

Upvotes: 1

Related Questions