【问题标题】:Aggregate two data frame by duplicated rows only仅按重复行聚合两个数据框
【发布时间】:2017-05-01 13:22:50
【问题描述】:

我使用聚合函数来总结重复行和唯一行,并在两个数据帧(df 和 nm)中找到公共列的平均值,即

df
User    Apple   Cherry  Kiwi    Lemon
A       208      71     129     58
B       81       69     142     53
C       164      212    175     200
D       125      73     51      214
E       205      123    46      75
F       53      215     40      38

nm
User    Lemon   Cherry  Apple   Kiwi
A        161     57      27      38
B        26      153     57      45
C        39      153     219     86
D        47      155     139     61

kl = aggregate(.~User, data=rbind(df, nm[, match(colnames(df), colnames(nm))]), FUN=mean)

它显示重复行和唯一行的输出。

kl
User    Apple   Cherry  Kiwi    Lemon
A       117.5    64     83.5    109.5
B       69       111    93.5    39.5
C       191.5    182.5  130.5   119.5
D       132      114    56      130.5
E       205      123    46      75
F       53      215     40      38

But  wanted output of only duplicated rows i.e. unique rows should be removed.

 kl
    User    Apple   Cherry  Kiwi    Lemon
    A       117.5    64     83.5    109.5
    B       69       111    93.5    39.5
    C       191.5    182.5  130.5   119.5
    D       132      114    56      130.5

我怎样才能使用上面的公式来做到这一点。

我试图找到这个答案,但到处都显示了重复和独特的示例。

请提供解决方案!!

谢谢

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用%in%rbinding 之前的“df”行进行子集化

    aggregate(.~User, rbind(df[df$User %in% nm$User,], nm), FUN = mean)
    #   User Apple Cherry  Kiwi Lemon
    #1    A 117.5   64.0  83.5 109.5
    #2    B  69.0  111.0  93.5  39.5
    #3    C 191.5  182.5 130.5 119.5
    #4    D 132.0  114.0  56.0 130.5
    

    或者如果我们使用match

    aggregate(.~User, rbind(df[match(df$User, nm$User, nomatch = 0),], nm), FUN = mean)
    

    如果我们只对常见的Users 感兴趣,另一种选择是intersect


    在 OP 的代码中,match 用于对列进行子集化,而两个数据集中的列相同。

    【讨论】:

    • 谢谢阿克伦!!它就像魅力一样。我的数据集很大,有没有其他方法可以更快地完成相同的活动。
    猜你喜欢
    • 1970-01-01
    • 2021-02-05
    • 2021-03-22
    • 2018-09-19
    • 2019-06-25
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多