【问题标题】:aggregating monthly sums and then getting the mean of all monthly sums汇总每月总和,然后获得所有每月总和的平均值
【发布时间】:2012-02-06 16:53:14
【问题描述】:

下面的列表是使用以下sn-p的时间序列中每个月对应的数据总和:

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)

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

【问题讨论】:

  • 我不知道为什么它没有出现在这里,但有人提到'为什么不采取平均水平?'。不能这样做,因为数据是能量,所以我需要先对数据求和以获得每个月的总能量。然后我想得到所有这些每月总和的平均值以获得 12 个平均值(每月 1 个)。

标签: r aggregate


【解决方案1】:

您也可以通过一次调用 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))}
           )

【讨论】:

    【解决方案2】:

    您可以使用 2 个 aggregate 语句来做到这一点:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2023-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多