bumblebee
bumblebee

Reputation: 1116

from two lists to one by binding elements

I have two lists with two elements each,

l1 <- list(data.table(id=1:5, group=1), data.table(id=1:5, group=1))
l2 <- list(data.table(id=1:5, group=2), data.table(id=1:5, group=2))

and I would like to rbind(.) both elements, resulting in a new list with two elements.

> l
[[1]]
    id group
 1:  1     1
 2:  2     1
 3:  3     1
 4:  4     1
 5:  5     1
 6:  1     2
 7:  2     2
 8:  3     2
 9:  4     2
10:  5     2

[[2]]
    id group
 1:  1     1
 2:  2     1
 3:  3     1
 4:  4     1
 5:  5     1
 6:  1     2
 7:  2     2
 8:  3     2
 9:  4     2
10:  5     2

However, I only find examples where rbind(.) is applied to bind across elements. I suspect that the solution lies somewhere in lapply(.) but lapply(c(l1,l2),rbind) appears to bind the lists, producing a list of four elements.

Upvotes: 1

Views: 91

Answers (2)

akrun
akrun

Reputation: 887391

Using tidyverse

library(tidyverse0
map2(l1, l2, bind_rows)

Upvotes: 0

emilliman5
emilliman5

Reputation: 5966

You can use mapply or Map. mapply (which stands for multivariate apply) applies the supplied function to the first elements of the arguments and then the second and then the third and so on. Map is quite literally a wrapper to mapply that does not try to simplify the result (try running mapply with and without SIMPLIFY=T). Shorter, arguments are recycled as necessary.

mapply(x=l1, y=l2, function(x,y) rbind(x,y), SIMPLIFY = F)
#[[1]]
#    id group
# 1:  1     1
# 2:  2     1
# 3:  3     1
# 4:  4     1
# 5:  5     1
# 6:  1     2
# 7:  2     2
# 8:  3     2
# 9:  4     2
#10:  5     2
#
#[[2]]
#    id group
# 1:  1     1
# 2:  2     1
# 3:  3     1
# 4:  4     1
# 5:  5     1
# 6:  1     2
# 7:  2     2
# 8:  3     2
# 9:  4     2
#10:  5     2

As @Parfait pointed out you can do this Map:

Map(rbind, l1, l2)
#[[1]]
#    id group
# 1:  1     1
# 2:  2     1
# 3:  3     1
# 4:  4     1
# 5:  5     1
# 6:  1     2
# 7:  2     2
# 8:  3     2
# 9:  4     2
#10:  5     2
#
#[[2]]
#    id group
# 1:  1     1
# 2:  2     1
# 3:  3     1
# 4:  4     1
# 5:  5     1
# 6:  1     2
# 7:  2     2
# 8:  3     2
# 9:  4     2
#10:  5     2

Upvotes: 5

Related Questions