创建 table 时求和列

Sum column when creating table

我在 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

并希望像这样在 table 中获取它:

     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 列的计数作为邻接 table 中的值。有小费吗?

你可以试试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 将 NA 替换为 0

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

或者正如@David Arenburg 提到的那样,这也可以通过 reshape2tidyr

等包来完成
 library(reshape2)
 acast(df1, origin~destination, value.var='amount', sum)