2015-05-21 60 views
1

我在[R以下数据帧:总和列的表

origin destination amount 
1  1   2  50 
2  1   2 100 
3  1   2  20 
4  1   3 100 
5  2   3  30 
6  2   3  50 
7  2   1  20 
8  3   2  10 
9  3   2  40 
10  3   1  50 

,并希望得到它在这样的桌子:

 1 2 3 
    1 0 170 100 
    2 20 0 80 
    3 50 50 0 

我认为它应该是table功能,但这只让我以下:

1 2 3 
1 0 3 1 
2 1 0 2 
3 1 2 0 

和我无法弄清楚如何获得amount列的计数值作为连接表中的值。有小费吗?

回答

2

您可以尝试xtabs

xtabs(amount~origin+destination, df1) 
#  destination 
#origin 1 2 3 
#  1 0 170 100 
#  2 20 0 80 
#  3 50 50 0 

或者使用tapply AMD与0

with(df1, tapply(amount, list(origin, destination), FUN=sum)) 

或者作为@大卫Arenburg提到的,这可能是与像reshape2包也做替换NAtidyr

library(reshape2) 
acast(df1, origin~destination, value.var='amount', sum) 
+1

你打算添加'dcast'和'spread'还是将它留给Hadleyverse的粉丝? :) –

+0

@DavidArenburg谢谢你提醒我。我只是在考虑基本的R选项,因为OP在表 – akrun

+1

@DavidArenburg'spread'有问题时给出了重复标识符的错误。所以,它可能需要几个步骤才能做到。我将把它开放给粉丝俱乐部:-) – akrun