【问题标题】:Average of month's data (jan-dec) in xts objectsxts 对象中月份数据的平均值(1 月至 12 月)
【发布时间】:2020-10-10 08:16:03
【问题描述】:

我有这么大的 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

的解决方案

我尝试在几年内拆分 xts

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

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

【问题讨论】:

标签: r split lapply xts do.call


【解决方案1】:

假设输入数据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)

【讨论】:

  • 这个解决方案的 NA 有问题。我在哪里可以使用类似 na.rm=T 的选项?
  • 是的,支持。已修改。
  • 作为进一步的评论,我想说这个 aggregate.zoo 即使有多个列 xts 对象也能很好地工作,它返回 每个列分别的月平均值。
【解决方案2】:

您可以使用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

【讨论】:

  • 它的工作原理谢谢!。有没有办法按 Jan-Dec Order 对输出进行排序?
  • 应该类似于 ans[match(month.name, rownames(ans)),]
  • 使用 lubridate::month 代替 base::months 工作正常。 do.call(rbind, lapply(split(x, lubridate::month(index(x))), mean, na.rm=TRUE))
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2015-12-10
    相关资源
    最近更新 更多