【问题标题】:How to use full_join/Reduce on multiple datasets AND have custom suffixes?如何在多个数据集上使用 full_join/Reduce 并具有自定义后缀?
【发布时间】:2021-12-26 02:42:46
【问题描述】:

我整天都在尝试合并/连接三个不同且重叠的行和列的数据集。 现在我一直在关注本教程:https://www.youtube.com/watch?v=L8NxjZCrzQY 取得了适度的成功。 不幸的是,我指定的后缀只显示在前两个数据集上,而不是第三个 (D3)。这些列只有它们的“正常”名称,即“var1”而不是“var1.a3”。 有谁知道我该如何解决这个问题?

谢谢!

 DATA <- list(D1, D2, D3)
DATAMERGE <- function(df1, df2){                             
  merge(df1, df2, by = "email", suffixes = c(".a1",".a2",".a3"))
}
RESULT<-Reduce(DATAMERGE, DATA)                                   
View(RESULT)

【问题讨论】:

  • 您能否提供问题中使用的D1D2D3 的样本?

标签: r join merge reduce


【解决方案1】:

实现所需结果的一种方法是在合并数据集之前通过重命名数据集的列来添加后缀。为此,我使用mapply 循环遍历您的数据集列表和后缀向量。

由于您没有提供任何数据,我使用 iris 作为示例数据集,并在 Species 上合并:

DATA <- list(D1 = iris, D2 = iris, D3 = iris)
suffixes <- c(".a1",".a2", ".a3")

DATAMERGE <- function(x, y) {
  merge(x, y, by = "Species")
}
DATA <- mapply(function(x, y) {
  z <- !names(x) %in% c("Species")
  names(x)[z] <- paste0(names(x)[z], y)
  x
}, DATA, suffixes, SIMPLIFY = FALSE)
RESULT <- Reduce(DATAMERGE, DATA)

head(RESULT)
#>   Species Sepal.Length.a1 Sepal.Width.a1 Petal.Length.a1 Petal.Width.a1
#> 1  setosa             5.1            3.5             1.4            0.2
#> 2  setosa             5.1            3.5             1.4            0.2
#> 3  setosa             5.1            3.5             1.4            0.2
#> 4  setosa             5.1            3.5             1.4            0.2
#> 5  setosa             5.1            3.5             1.4            0.2
#> 6  setosa             5.1            3.5             1.4            0.2
#>   Sepal.Length.a2 Sepal.Width.a2 Petal.Length.a2 Petal.Width.a2 Sepal.Length.a3
#> 1             5.1            3.5             1.4            0.2             5.1
#> 2             5.1            3.5             1.4            0.2             4.9
#> 3             5.1            3.5             1.4            0.2             4.7
#> 4             5.1            3.5             1.4            0.2             4.6
#> 5             5.1            3.5             1.4            0.2             5.0
#> 6             5.1            3.5             1.4            0.2             5.4
#>   Sepal.Width.a3 Petal.Length.a3 Petal.Width.a3
#> 1            3.5             1.4            0.2
#> 2            3.0             1.4            0.2
#> 3            3.2             1.3            0.2
#> 4            3.1             1.5            0.2
#> 5            3.6             1.4            0.2
#> 6            3.9             1.7            0.4

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2023-03-15
    • 1970-01-01
    • 2019-08-04
    • 2021-08-11
    相关资源
    最近更新 更多