【问题标题】:Right join multiple dataframe by one column按一列右连接多个数据框
【发布时间】:2019-11-22 13:00:17
【问题描述】:

我有这三个数据框df1、df2、df3。

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),但它不起作用。我在这里做错了什么?

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

【问题讨论】:

  • 当你说doesn't work时,有什么错误吗?我能够运行您的代码而不会出现任何错误。请注意,当所有列中的 key 元素重复时,行将被重复,因为它不是特定的连接
  • @akrun 它没有像cbind(df1,df2$SD, df3$Count)那样给我预期的结果。
  • 因为您对所有数据集的 by 列都有欺骗
  • 一种方法是在所有数据集中通过“ControlRate”创建一个序列列,然后将两列合并
  • 您可能需要Reduce(function(...) merge(..., by = c("ControlRate", "grp"), all.x = TRUE), lapply(list(df1, df2, df3), transform, grp = ave(seq_along(ControlRate), ControlRate, FUN = seq_along)))

标签: r dplyr mapreduce reduce right-join


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 2017-11-17
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多