我可以为acast中的不同列设置不同的聚合规则吗?

时间:2013-10-24 15:51:27

标签: r aggregate reshape2

今天的脑功能:我如何告诉acast返回不同的聚合?

# the rows and columns have integer names
Rgames> foo
  1 2
1 1 1
2 2 2
3 3 3
4 4 4
1 1 4
2 2 8
3 3 2
4 4 1
Rgames> mfoo<-melt(foo)
Rgames> mfoo
   Var1 Var2 value
1     1    1     1
2     2    1     2
3     3    1     3
4     4    1     4
5     1    1     1
6     2    1     2
7     3    1     3
8     4    1     4
9     1    2     1
10    2    2     2
11    3    2     3
12    4    2     4
13    1    2     4
14    2    2     8
15    3    2     2
16    4    2     1
Rgames> acast(mfoo,Var1~Var2,function(x)x[1]-x[2])
  1  2
1 0 -3
2 0 -6
3 0  1
4 0  3
# what I would like is the casting formula to return
  1  2
1 1 -3
2 2 -6
3 3  1
4 4  3

请注意,这是一个简单的例子。在一般情况下,将会有具有唯一名称的行 - 但是具有给定名称的行不会超过两行,因此我的x[1]-x[2]将不会失败。 或者我应该使用它:

aggregate(foo[,2],by=list((foo[,1])),function(x)x[1]-x[2])

0 个答案:

没有答案