本文介绍了如何将R中公共列上的两个数据帧与其他数据之和合并?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
data_B
USER_A USER_B ACTION
1 13 0.17
1 14 0.27
2 11 0.25
现在,如果USER_A和USER_B相等,我想将data_B的ACTION添加到data_A.如上例所示,结果将是:
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))
请注意,使用参数all.x=TRUE
调用了merge
-这将返回传递给merge
的第一个data.frame中的所有值,即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中公共列上的两个数据帧与其他数据之和合并?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!