littleworth
littleworth

Reputation: 5169

How to rbind (concatenate) dataframes stored as element of list of list

I have the following list of data frames:

l = list()
l[[1]] = list(A=iris[1:3,], B=mtcars[1:3,])
l[[2]] = list(A=iris[5:8,], B=mtcars[5:8,])

What I want to do is to concatenate only A element of the list; resulting in:

Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
7          4.6         3.4          1.4         0.3  setosa
8          5.0         3.4          1.5         0.2  setosa

I tried this but it doesn't give what I want:

> do.call(rbind, l)
     A      B      
[1,] List,5 List,11
[2,] List,5 List,11

What's the right way to do it?

Upvotes: 2

Views: 53

Answers (3)

mharinga
mharinga

Reputation: 1780

Easy solution using purrr:

purrr::map_dfr(l, "A")

Upvotes: 2

Sotos
Sotos

Reputation: 51582

You can try with Reduce and Map. Map will bind the data frames one-by-one while the Reduce makes sure that It will do it for all the elements in your list.

Reduce(function(...)Map(function(x, y)rbind(x, y), ...), l)

$A
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
7          4.6         3.4          1.4         0.3  setosa
8          5.0         3.4          1.5         0.2  setosa

$B
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

Upvotes: 2

StupidWolf
StupidWolf

Reputation: 46898

Or simply just call out the "A" element using lapply

do.call(rbind,lapply(l,"[[","A"))

Upvotes: 1

Related Questions