r - 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?
解决方案
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
推荐阅读
- apache-pig - 如何连接元组,哪些元组在包中
- java - 将表 wp_users(Wordpress) 转换为表用户(Java) - 安全登录
- swift - 无法在 Firebase 中使用 geoFire 存储 CLLocation 对象
- c# - 无法加载类型
- azure-sdk-.net - 2019 年 7 月从 QnAMaker 知识库获取答案的最新方法是什么?
- javascript - 如何过滤保留原始组结果的先前正则表达式组的结果
- python - 为什么我不能在 Tensorflow 中初始化或评估我的变量?
- javascript - 如何使用它们的值处理多个选择下拉组件?
- android - 如何锁定 Termux 包环境版本
- python - 使用 opencv 去除 OCR 的背景噪声