首页 > 解决方案 > How to merge dataframe within a list by the same name in R?

问题描述

I have a list which contains a lot of dataframe. I want to merge them if they have the same name,i.e. merge all the dataframe which have the same name "a" and "b". Like this

a <- "aaaaa"
b <- "bbbbb"
c <- "ccccc"

g <- list(df1 <- data.frame(a,b), mf2 <- data.frame(b,b),
      mf1 <- data.frame(c,b), df2 <- data.frame(a,c),
      mf3 <- data.frame(b,c))
names(g) <- c("a","b","a","b","c")
> g
$`a`
      a     b
1 aaaaa bbbbb
$b
      b   b.1
1 bbbbb bbbbb
$a
      c     b
1 ccccc bbbbb
$b
      a     c
1 aaaaa ccccc
$c
      b     c
1 bbbbb ccccc
#I want to merge them by names and ideal result should be
$`a`
      a     b     c     b
1 aaaaa bbbbb ccccc bbbbb
$b
      b   b.1     a     c
1 bbbbb bbbbb aaaaa ccccc
$c
      b     c
1 bbbbb ccccc

I want to merge them by names and ideal result should be like the one up there. How can I do that?

标签: rlistdataframemerge

解决方案


Here is a tidyverse solution. We can split the list by name and then use bind_cols to combine the data frame for each group.

library(tidyverse)

g2 <- map(split(g, names(g)), bind_cols)
g2
# $`a`
#       a     b     c    b1
# 1 aaaaa bbbbb ccccc bbbbb
# 
# $b
#       b   b.1     a     c
# 1 bbbbb bbbbb aaaaa ccccc
# 
# $c
#       b     c
# 1 bbbbb ccccc

The base R equivalent is as follows.

g2 <- lapply(split(g, names(g)), function(x) do.call(cbind, x))
g2
# $`a`
#     a.a   a.b   a.c   a.b
# 1 aaaaa bbbbb ccccc bbbbb
# 
# $b
#     b.b b.b.1   b.a   b.c
# 1 bbbbb bbbbb aaaaa ccccc
# 
# $c
#     c.b   c.c
# 1 bbbbb ccccc

推荐阅读