如何在R中合并这两个数据集

时间:2015-07-22 18:09:18

标签: r dataset

如何合并这两个数据集以填充N / A.

示例 - >

Name Abbreviation Denomination
-------------------------------
Asia     A             N/A
Bob      B             N/A
Chris    C             N/A
David    D             N/A

合并

Name Abbreviation Denomination
-------------------------------
Asia     A             5
Bradley  BA            1
Chris    C             7
David    D             9
Emma     EM            2
Soo      So            4
Nate     NT            2
Bob      B             1
Brat     B             5
Asia     S             2

如何合并这两套,以便获得:

Name Abbreviation Denomination
-------------------------------
Asia     A             5
Bob      B             1
Chris    C             7
David    D             9

2 个答案:

答案 0 :(得分:1)

我认为有一种聪明的方法可以获得,但这是我笨拙的解决方案:

 df3 <- merge(df1, df2, by = c("Name", "Abbreviation"))
 df3
   Name Abbreviation Denomination.x Denomination.y
1  Asia            A            N/A              5
2   Bob            B            N/A              1
3 Chris            C            N/A              7
4 David            D            N/A              9

然后使用Denomination.x

删除列df3 <- df3[, -3]
df3
   Name Abbreviation Denomination.y
1  Asia            A              5
2   Bob            B              1
3 Chris            C              7
4 David            D              9

答案 1 :(得分:0)

试试这个:

x <- data.frame(Name = c("Asia", "Bradley", "Chris", "David", "Emma", "Soo", "Nate", 
                     "Bob", "Brat", "Asia"),
            Abb = c("A", "BA", "C", "D", "EM", "So", "NT", "B", "B", "S"),
            Den = c(5, 1, 7, 9, 2, 4, 2, 1, 5, 2))

y <- data.frame(Name = c("Asia", "Bob", "Chris", "David"), Abb = c("A","B", "C", "D"),
            Den = c("NA", "NA", "NA", "NA"))

data_df <- merge(x, y , by = 1)

subset(data_df, Abb.x != "S", c(1,2,3))


     Name Abb.x Den.x
  1  Asia     A     5
  3   Bob     B     1
  4 Chris     C     7
  5 David     D     9

您始终可以将列等重命名为您希望的名称。