如何将 R 中公共列上的两个数据框与其他数据框的总和合并? [英] How to merge two data frames on common columns in R with sum of others?
本文介绍了如何将 R 中公共列上的两个数据框与其他数据框的总和合并?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Windows 7 上的 R 版本 2.11.1 32 位
R Version 2.11.1 32-bit on Windows 7
我得到了两个数据集:data_A 和 data_B:
I got two data sets: data_A and data_B:
USER_A USER_B ACTION
1 11 0.3
1 13 0.25
1 16 0.63
1 17 0.26
2 11 0.14
2 14 0.28
数据_B
USER_A USER_B ACTION
1 13 0.17
1 14 0.27
2 11 0.25
现在我想将 data_B 的 ACTION 添加到 data_A 中,如果它们的 USER_A 和 USER_B 相等.如上例,结果为:
Now I want to add the ACTION of data_B to the data_A if their USER_A and USER_B are equal. As the example above, the result would be:
USER_A USER_B ACTION
1 11 0.3
1 13 0.25+0.17
1 16 0.63
1 17 0.26
2 11 0.14+0.25
2 14 0.28
那我怎么能做到呢?
推荐答案
您可以使用 plyr
包中的 ddply
并与 merge
结合:
You can use ddply
in package plyr
and combine it with merge
:
library(plyr)
ddply(merge(data_A, data_B, all.x=TRUE),
.(USER_A, USER_B), summarise, ACTION=sum(ACTION))
注意 merge
使用参数 all.x=TRUE
调用 - 这将返回传递给 merge<的第一个 data.frame 中的所有值/code>,即 data_A:
Notice that merge
is called with the parameter all.x=TRUE
- this returns all of the values in the first data.frame passed to merge
, i.e. data_A:
USER_A USER_B ACTION
1 1 11 0.30
2 1 13 0.25
3 1 16 0.63
4 1 17 0.26
5 2 11 0.14
6 2 14 0.28
这篇关于如何将 R 中公共列上的两个数据框与其他数据框的总和合并?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文