### 計算ts對象的月平均值

#### [英]Calculate monthly average of ts object

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...

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))
``````

## 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:

``````> 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?