Suppose I have the following two lists. I want to take the first entry of list2 and combine this data frame to list1. Doing this for all entries.
data1 <- data.frame(id = 1:6,
x1 = c(5, 1, 4, 9, 1, 2),
x2 = c("A", "Y", "G", "F", "G", "Y"))
data2 <- data.frame(id = 4:9,
y1 = c(3, 3, 4, 1, 2, 9),
y2 = c("a", "x", "a", "x", "a", "x"))
l1 <- list(data1, data2)
l2 <- list(data1, data2)
What I expect as a result is one list of length 2. Each entry should be a data frame with 12 rows and 3 columns.
CodePudding user response:
We may use Map
with rbind
to rbind the corresponding data.frame elements from both list
s
Map(rbind, l1, l2)
-output
[[1]]
id x1 x2
1 1 5 A
2 2 1 Y
3 3 4 G
4 4 9 F
5 5 1 G
6 6 2 Y
7 1 5 A
8 2 1 Y
9 3 4 G
10 4 9 F
11 5 1 G
12 6 2 Y
[[2]]
id y1 y2
1 4 3 a
2 5 3 x
3 6 4 a
4 7 1 x
5 8 2 a
6 9 9 x
7 4 3 a
8 5 3 x
9 6 4 a
10 7 1 x
11 8 2 a
12 9 9 x
Or using map2
from purrr
library(purrr)
library(dplyr)
map2(l1, l2, bind_rows)
CodePudding user response:
Another possible solution, based on mapply
:
mapply(rbind, l1, l2, SIMPLIFY = F)
#> [[1]]
#> id x1 x2
#> 1 1 5 A
#> 2 2 1 Y
#> 3 3 4 G
#> 4 4 9 F
#> 5 5 1 G
#> 6 6 2 Y
#> 7 1 5 A
#> 8 2 1 Y
#> 9 3 4 G
#> 10 4 9 F
#> 11 5 1 G
#> 12 6 2 Y
#>
#> [[2]]
#> id y1 y2
#> 1 4 3 a
#> 2 5 3 x
#> 3 6 4 a
#> 4 7 1 x
#> 5 8 2 a
#> 6 9 9 x
#> 7 4 3 a
#> 8 5 3 x
#> 9 6 4 a
#> 10 7 1 x
#> 11 8 2 a
#> 12 9 9 x