一列右连接多个数据框

时间:2019-07-12 18:32:54

标签: r dplyr mapreduce reduce right-join

我有这三个数据帧df1df2df3

df1<- structure(list(ControlRate = structure(c(1L, 1L, 1L), .Label = c("24000", 
"26000", "28000", "30000"), class = "factor"), Mean = c(92.914223793805, 
125.810174859037, 152.350610715905)), row.names = c(NA, 3L), class = "data.frame")

df2 <- structure(list(ControlRate = structure(c(1L, 1L, 1L), .Label = c("24000", 
"26000", "28000", "30000"), class = "factor"), SD = c(19.7498590603068, 
33.5137097117632, 40.4792131612947)), row.names = c(NA, 3L), class = "data.frame")

df3 <- structure(list(ControlRate = structure(c(1L, 1L, 1L), .Label = c("24000", 
"26000", "28000", "30000"), class = "factor"), Count = c(36L, 
117L, 198L)), row.names = c(NA, 3L), class = "data.frame")

我不想使用cbind(df1,df2$SD, df3$Count),而是想像下面那样使用merge,但是它不起作用。我在这里做什么错了?

Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "ControlRate", all.x = TRUE),
       list(df1, df2, df3))

1 个答案:

答案 0 :(得分:3)

library(tidyverse)

list(df1,df2,df3) %>%
  map(rowid_to_column) %>%
  reduce(left_join, by = c("rowid","ControlRate")) %>% 
  select(-rowid)

#>   ControlRate      Mean       SD Count
#> 1       24000  92.91422 19.74986    36
#> 2       24000 125.81017 33.51371   117
#> 3       24000 152.35061 40.47921   198