计算ts对象的月平均值 [英] Calculate monthly average of ts object
问题描述
给定每月 ts 对象,例如:
Given a monthly ts object such as this:
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...
我想到的一种方法是将其转换为 12 列的矩阵并使用 colMeans()
,但我想有一种更好的方法可以利用 time()
ts()
对象的 code> 方面?
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?
colMeans(matrix(dat, ncol = 12, byrow = TRUE))
推荐答案
好的,所以我应该在来 SO 之前再给 Google 一次搜索,因为这个 帖子是相关的.cycle()
函数似乎对这些事情很有用:
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:
> 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?
这篇关于计算ts对象的月平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!