当多个数据集中存在相同的列名时,应使用哪个合并命令进行合并?

时间:2018-06-29 04:52:04

标签: r

三个数据集如下:

[Name]  [10th]  [Mark]
Ram     ICSE    562
Sam     CBSE    589
Deep    CBSE    523

[Name]  [12th]  [Mark]
Ram     PCM     589
Sam     CBZ     689
Deep    PCM     563

[Name]  [B.Tech]    [Mark]
Ram         Mech    589
Sam        Civil    689
Deep          IT    563

我希望以以下格式输出:

[Name]  [10th]  [Mark]  [12th]  [Mark]  [B.Tech]    [Mark]
Ram     ICSE    562      PCM    589        Mech     589
Sam     CBSE    589      CBZ    689        Civil    689
Deep    CBSE    523      PCM    563           IT    563

请帮助我。

1 个答案:

答案 0 :(得分:0)

我们可以将purrr::reducedplyr::full_join一起使用

library(tidyverse);
reduce(list(df1, df2, df3), function(x, y) full_join(x, y, by = "Name"))
#  Name X10th Mark.x X12th Mark.y B.Tech Mark
#1  Ram  ICSE    562   PCM    589   Mech  589
#2  Sam  CBSE    589   CBZ    689  Civil  689
#3 Deep  CBSE    523   PCM    563     IT  563 

或在基数R中:

Reduce(function(x, y) merge(x, y, by = "Name"), list(df1, df2, df3))
#  Name X10th Mark.x X12th Mark.y B.Tech Mark
#1 Deep  CBSE    523   PCM    563     IT  563
#2  Ram  ICSE    562   PCM    589   Mech  589
#3  Sam  CBSE    589   CBZ    689  Civil  689

样本数据

df1 <- read.table(text =
    "Name   10th     Mark
Ram        ICSE    562
Sam        CBSE    589
Deep    CBSE    523", header = T);

df2 <- read.table(text =
    "Name    12th    Mark
Ram        PCM        589
Sam        CBZ        689
Deep    PCM        563", header = T);

df3 <- read.table(text =
    "Name    B.Tech    Mark
Ram            Mech    589
Sam           Civil    689
Deep          IT    563", header  = T)