我有以下3个数据帧(不是tibble):
dat1 <- structure(c(0.033, 0.066, 0.233,
0.0333333333333333), .Dim = c(2L, 2L), .Dimnames = list(c("A",
"B"), c("Xxx", "Yyy")))
dat2 <- structure(c(0.1, 0, 0.1, 0.033), .Dim = c(2L, 2L
), .Dimnames = list(c("A", "B"), c("Aaa", "Rrr")))
dat3 <- structure(c(0.2, 0.02, 0.2, 0.03), .Dim = c(2L, 2L
), .Dimnames = list(c("A", "C"), c("Aaa", "Ggg")))
dat1
#> Xxx Yyy
#> A 0.033 0.23300000
#> B 0.066 0.03333333
dat2
#> Aaa Rrr
#> A 0.1 0.100
#> B 0.0 0.033
dat3
#> Aaa Ggg
#> A 0.20 0.20
#> C 0.02 0.03
我想将3个/ left_join合并到最终数据框中(不是tibble):
Xxx Yyy Aaa Rrr Aaa.2 Ggg
A 0.033 0.233 0.100 0.100 0.200 0.200
B 0.066 0.033 0.000 0.033 NA NA
C NA NA NA NA 0.02 0.03
我该怎么做?
我尝试了这个但是没有工作:
> l <- list(dat1, dat2, dat3)
> Reduce(merge, lapply(l, function(x) data.frame(x, rn = row.names(x))))
[1] rn Aaa Xxx Yyy Rrr Ggg
<0 rows> (or 0-length row.names)
答案 0 :(得分:3)
我们创建一个列名,然后进行连接
library(tidyverse)
list(dat1, dat2, dat3) %>%
map(~ .x %>%
as.data.frame %>%
rownames_to_column('rn')) %>%
reduce(full_join, by = 'rn') %>%
column_to_rownames('rn')
# Xxx Yyy Aaa.x Rrr Aaa.y Ggg
#A 0.033 0.23300000 0.1 0.100 0.20 0.20
#B 0.066 0.03333333 0.0 0.033 NA NA
#C NA NA NA NA 0.02 0.03
答案 1 :(得分:3)
您需要在by
Reduce(function(x, y) merge(x, y, all=TRUE, by="rn", suffixes=c("", ".2")),
lapply(list(dat1, dat2, dat3),
function(x) data.frame(x, rn = row.names(x))))
# rn Xxx Yyy Aaa Rrr Aaa.2 Ggg
#1 A 0.033 0.23300000 0.1 0.100 0.20 0.20
#2 B 0.066 0.03333333 0.0 0.033 NA NA
#3 C NA NA NA NA 0.02 0.03