嗨我有两个数据框:
df1 = data.frame(PersonId1=c(1,2,3,4,5,6,7,8,9,10,1),PersonId2=c(11,12,13,14,15,16,17,18,19,20,11),
Played_together = c(1,0,0,1,1,0,0,0,1,0,1),
Event=c(1,1,1,1,2,2,2,2,2,2,2),
Utility=c(20,-2,-5,10,30,2,1,.5,50,-1,60))
df2 = data.frame(PersonId1=c(11,15,9,1),PersonId2=c(1,5,19,11),
Played_together = c(1,1,1,1),
Event=c(1,2,2,2))
df1 看起来像这样:
PersonId1 PersonId2 Played_together Event Utility
1 1 11 1 1 20.0
2 2 12 0 1 -2.0
3 3 13 0 1 -5.0
4 4 14 1 1 10.0
5 5 15 1 2 30.0
6 6 16 0 2 2.0
7 7 17 0 2 1.0
8 8 18 0 2 0.5
9 9 19 1 2 50.0
10 10 20 0 2 -1.0
11 1 11 1 2 60.0
df2 看起来像这样:
PersonId1 PersonId2 Played_together Event
1 11 1 1 1
2 15 5 1 2
3 9 19 1 2
4 1 11 1 2
请注意 df2 并不简单df1$played_together==1。 (例如 PlayerId1 = 4 且 PlayerId2=14 不存在于 df2 中。
另请注意,虽然 df2 是 df1 的子集,但个体出现在 df2 中的顺序是随机的。例如在df1在第 1 行中,我们看到事件 1 的playerid1 = 1 和playerId2 = 11。但是在df2在第 1 行中,我们看到事件 1 的playerid1 = 11 和playerId2 = 1。这两种情况完全相同,我想查找以下值Utility from df1 to df2。每个事件都必须进行合并。最终输出应如下所示:
PersonId1 PersonId2 Played_together Event Utility
1 11 1 1 1 20
2 15 5 1 2 30
3 9 19 1 2 50
4 1 11 1 2 60
我知道 R 中存在合并函数,但我不知道当查找 id 可以随机出现时该怎么办。如果有人能帮助我一点,我将不胜感激。提前致谢。