計算ts對象的月平均值

[英]Calculate monthly average of ts object


Given a monthly ts object such as this:

鑒於每月ts對象如下:

dat <- ts(c(295, 286, 300, 278, 272, 268, 308, 321, 313, 308, 291, 296, 
294, 273, 300, 271, 282, 285, 318, 323, 313, 311, 291, 293, 297, 
273, 294, 259, 276, 294, 316, 325, 315, 312, 292, 301), frequency = 12)

How can I calculate averages by month? i.e. I want to calculate the average of January, year1 + January, year2 + January, year 3...etc. and then be able to draw comparisons to the February's...

如何按月計算平均值?即我想計算1月,1年+ 1月,2年+ 1月,3年等的平均值。然后能夠比較二月的...

One approach I thought of was to turn it into a matrix of 12 columns and use colMeans(), but I imagine there is a better way that leverages the time() aspect of the ts() object?

我想到的一種方法是將其轉換為12列的矩陣並使用colMeans(),但我想有一種更好的方法可以利用ts()對象的time()方面?

colMeans(matrix(dat, ncol = 12, byrow = TRUE))

1 个解决方案

#1


9  

Ok, so I should given Google one more search before coming to SO as this post is relevant. The cycle() function appears to be useful for these sorts of things:

好的,所以我應該在進入SO之前再給Google一次搜索,因為這篇文章是相關的。 cycle()函數似乎對這些事情很有用:

> tapply(dat, cycle(dat), mean)
        1         2         3         4         5         6         7         8         9 
295.33333 277.33333 298.00000 269.33333 276.66667 282.33333 314.00000 323.00000 313.66667 
       10        11        12 
310.33333 291.33333 296.66667

> aggregate(c(dat), list(month = cycle(dat)), mean) 
   month         x
1      1 295.33333
2      2 277.33333
3      3 298.00000
....

Anything else fundamental I'm missing here?

我還缺少其他基本的東西嗎?


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/06/30/4c3f59f5425c29b46432052207f31184.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com