简体   繁体   中英

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!

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

Here is an option with ==

names(my_list) %>% 
     unique %>% 
     map(~ my_list[names(my_list)==.x] %>% 
       bind_rows)
#[[1]]
#  a1 b1 c1
#1  1  3  5
#2  2  4  6
#3 11 31 51
#4 21 41 61

#[[2]]
#  b1
#1  1
#2  2
#3  3
#4 12
#5 22

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM