【问题标题】:Merge with duplicates values in R与 R 中的重复值合并
【发布时间】:2018-03-21 21:08:26
【问题描述】:

我有两个数据框

db1 喜欢:

date.prix;var1;var2
2012-10-02;pluf;plof
2012-12-11;pam;pim
2013-05-17;plop;plip
...

db2 喜欢:

date.de.cotation;var3;var4
2012-10-02;tutu;toto
2012-10-02;ting;tong
2013-05-17;gui;guou
...

连接是 date.prix = date.de.cotation

我想要类似的东西:

date.prix;var1;var2;var3;var4
2012-10-02;pluf;plof;tutu;toto
2012-12-11;pam;pim;NA;NA
2013-05-17;plop;plip;gui;guou

所以:

  • 如果 db2 中有重复项,我想要第一个的值
  • 如果 db2 中没有日期值,我想要 NAs

【问题讨论】:

  • db2 中删除重复项并使用all.x = Tdb1db2 合并。

标签: r join merge duplicates


【解决方案1】:

data.table 中的左连接有一个mult 参数:mult='first' 将只保留db2 中的第一个匹配行。

library(data.table)

db1 <- fread('date.prix;var1;var2
2012-10-02;pluf;plof
2012-12-11;pam;pim
2013-05-17;plop;plip')

db2 <- fread('date.de.cotation;var3;var4
2012-10-02;tutu;toto
2012-10-02;ting;tong
2013-05-17;gui;guou')

# if db1 and db2 are not data.table, do: setDT(db1); setDT(db2);

db2[db1, on = .(date.de.cotation = date.prix), mult = 'first']
#    date.de.cotation var3 var4 var1 var2
# 1:       2012-10-02 tutu toto pluf plof
# 2:       2012-12-11   NA   NA  pam  pim
# 3:       2013-05-17  gui guou plop plip

【讨论】:

  • 这个命令有错误:Error in [.data.frame(base.concurrence2016, base.platts2016, on = .(date.de.cotation = date.prix), : unused arguments (on = .(date.de.cotation = date.prix), mult = "first")
  • @celianou,正如我在评论上述代码时所说,如果data.framesetDT(db1); setDT(db2)setDT(db1); setDT(db2),则应首先将db1db2 转换为data.table
【解决方案2】:

我们可以使用duplicatedmerge 函数:

db2_2 <- db2[!duplicated(db2$date.de.cotation), ] # remove everything but first instance
merge(db1, db2_2, by.x = 'date.prix', by.y = 'date.de.cotation', all.x = TRUE)

#    date.prix var1 var2 var3 var4
# 1 2012-10-02 pluf plof tutu toto
# 2 2012-12-11  pam  pim <NA> <NA>
# 3 2013-05-17 plop plip  gui guou

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2016-02-11
    • 2021-05-06
    • 2015-11-22
    • 2018-06-17
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多