Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind rows of the dataframes in a list with the same name

Apologies in advance if this has been answered already. I have the following list of dataframes.

 my_list <- list(a = data.frame(a1 = c(1,2), b1 = c(3,4), c1 =c(5,6)),
                 b = data.frame(b1 = c(1,2,3)),
                 a = data.frame(a1 = c(11,21), b1 = c(31,41), c1 =c(51,61)),
                 b = data.frame(b1 = c(12,22)))

How could I bind the rows of all the dataframes in my list with the same name using purr? In this example the desired result is a list with two dataframes a and b.

list(a = bind_rows(data.frame(a1 = c(1,2), b1 = c(3,4), c1 =c(5,6)),
                   data.frame(a1 = c(11,21), b1 = c(31,41), c1 =c(51,61))),
     b = bind_rows(data.frame(b1 = c(1,2)),
                   data.frame(b1 = c(12,22))))

How could I generalise with a bind_rows solution for list elements with the same name. Thanks!

like image 313
Christos Avatar asked Oct 15 '25 04:10

Christos


1 Answers

Use tapply with bind_rows, pass names(my_list) as the INDEX (or group variable):

tapply(my_list, names(my_list), dplyr::bind_rows)

#$a
#  a1 b1 c1
#1  1  3  5
#2  2  4  6
#3 11 31 51
#4 21 41 61

#$b
#  b1
#1  1
#2  2
#3  3
#4 12
#5 22

Or another option, split the list first and then map through each group and bind_rows (didn't notice @alistaire has provided this option in the comment, but will keep this option in the answer for completeness unless argued against):

library(purrr)

split(my_list, names(my_list)) %>% map(dplyr::bind_rows)
# could also use baseR solution as from @Rich Scriven 
# split(my_list, names(my_list)) %>% map(do.call, what='rbind')

#$a
#  a1 b1 c1
#1  1  3  5
#2  2  4  6
#3 11 31 51
#4 21 41 61

#$b
#  b1
#1  1
#2  2
#3  3
#4 12
#5 22
like image 141
Psidom Avatar answered Oct 17 '25 21:10

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!