xts 对象中月数据(一月到十二月)的平均值

Average of month's data (jan-dec) in xts objects

我有这么大的 xts,每月使用 apply.monthly 函数汇总。

2011-07-31 269.8
2011-08-31 251.0
2011-09-30 201.8
2011-10-31 95.8
2011-11-30 NA
2011-12-31 49.3
2012-01-31 77.1
...

我想要的是计算所有期间的 1 月至 12 月的平均值。类似这样的东西,但是在 xts 形式中:

01 541.8
02 23.0
03 34.8
04 12.8
05 21.8
06 44.8
07 22.8
08 55.0
09 287.8
10 15.8
11 113
12 419.3

我想避免使用 dplyr 函数,例如 group_by。我认为必须有一个使用 splitlapply / do.call[=33= 的解决方案]

我试过几年拆分 xts

xtsobject <- split(xtsobject, f = "years")

然后我不知道如何正确使用 lapply 函数来计算所有期间的 12 个平均值(1 月至 12 月)。 这个问题 类似,但是在我的xts中我没有have/want一个新的专栏,我认为可以使用xts索引来完成。

您可以使用base::months函数在计算平均值之前提取月份:

do.call(rbind, lapply(split(x, base::months(index(x))), mean, na.rm=TRUE))

输出:

              [,1]
April     165.1600
August    290.2444
December  106.8200
February   82.6300
January    62.9100
July      264.9889
June      246.4889
March     100.5500
May       246.3333
November  116.6400
October   151.3667
September 158.5667

索引似乎是一个数字而不是 POSIXct 对象。您可以转换它并使用 format 提取月份并在 tapply 中使用它:

tapply(xtsobject[, 1], format(as.POSIXct(zoo::index(xtsobject), 
                          origin = '1970-01-01'), '%m'), mean, na.rm = TRUE)

假设输入数据 x,在末尾的注释中重复显示,使用 aggregate.zoo 如下:

ag <- aggregate(x, cycle(as.yearmon(time(x))), mean, na.rm = TRUE)
ag

提供以下动物园系列:

1   77.1
7  269.8
8  251.0
9  201.8
10  95.8
11   NaN
12  49.3

我们可以这样画:

plot(ag, type = "h")

备注

Lines <- "2011-07-31 269.8
2011-08-31 251.0
2011-09-30 201.8
2011-10-31 95.8
2011-11-30 NA
2011-12-31 49.3
2012-01-31 77.1"

library(xts)
z <- read.zoo(text = Lines)
x <- as.xts(z)