2012-02-06 94 views
4

的平均下面的列表是使用下面的代码片断对应于每个月份的时间序列数据的总和:每月汇总金额,然后让所有款项每月

aggregate(data, by=list(Year=format(DateTime, "%Y"), Month=format(DateTime, "%m")), sum, na.rm=TRUE) 

Year Month  x 
1 1981 01 62426.43 
2 1982 01 70328.87 
3 1983 01 67516.34 
4 1984 01 64454.00 
5 1985 01 78801.46 
6 1986 01 73865.18 
7 1987 01 64224.96 
8 1988 01 72362.39 
9 1981 02 74835.16 
10 1982 02 75275.58 
11 1983 02 67457.39 
12 1984 02 64981.99 
13 1985 02 56490.10 
14 1986 02 62759.89 
15 1987 02 65144.44 
16 1988 02 67704.67 

这部分很简单......但我正在试图获得每个月所有的月度金额的平均值(即总和每个月的一个平均) 绊倒了。如果我执行以下操作:

aggregate(data, by=list(Month=format(DateTime, "%m")), sum, na.rm=TRUE) 

我只是得到所有的总和几个月的时间系列,这是我不想要的。我可以在一个汇总语句中实现所需的结果,还是需要更多的代码...任何帮助,将不胜感激。

+0

我不知道为什么它没有出现在这里了,但有人提到'为什么不要采取意思?'。由于数据是能量,所以我不能这样做,所以我需要首先总结数据以获得每个月的总能量。然后,我想要得到所有这些每月总和的平均值,以获得12个平均值(每月1个)。 – RWJ 2012-02-06 17:12:34

回答

4

你可以用2个aggregate语句做到这一点:

aggregate(x~Month, aggregate(data, by=list(Year=format(DateTime, "%Y"), Month=format(DateTime, "%m")), sum, na.rm=TRUE), mean) 
+0

完美...谢谢James – RWJ 2012-02-06 17:20:09

5

你也可以有一个单一的调用来完成它aggregate

aggregate(data, 
      by=list(Year=format(DateTime, "%Y"), Month=format(DateTime, "%m")), 
      FUN= function(x){ sum(x, na.rm=TRUE)/sum(!is.na(x))} 
      )