【问题标题】:Extract month mean from time series in R从R中的时间序列中提取月份平均值
【发布时间】:2012-08-16 12:54:38
【问题描述】:

我有一些数据格式如下:

    date     x     
    2001/06  9949 
    2001/07  8554  
    2001/08  6954 
    2001/09  7568 
    2001/10 11238  
    2001/11 11969 
    ... more rows

我想提取每个月的 x 平均值。我尝试了一些带有聚合的代码,但是 失败的。感谢您提供任何帮助。

【问题讨论】:

  • 看来你已经掌握了...
  • 没有数据继续:2002/01...2012/01, 2012/02。

标签: r time-series mean


【解决方案1】:

这里我用更多数据模拟了一个名为df的数据框:

df <- data.frame( 
      date = apply(expand.grid(2001:2012,1:12),1,paste,collapse="/"),
      x = rnorm(12^2,1000,1000),
      stringsAsFactors=FALSE)

使用date 向量的构造方式,您可以通过删除前四位数字和正斜杠来获得月份。在这里,我使用它作为tapply 中的索引变量来计算均值:

with(df, tapply(x, gsub("\\d{4}/","",date), mean))

【讨论】:

  • 请注意,结果是一个不同顺序的命名向量。这些名字给出了月份。
  • 是的,我看到了——这个重新排序实际上对我有帮助!
【解决方案2】:

抱歉...只需创建一个月序列向量,然后使用 tapply。 这很容易:

m.seq = rep(c(6:12, 1:5), length = nrow(data))
m.means = tapply(data$x, m.seq, mean)

不过还是感谢 cmets!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2021-07-15
    • 1970-01-01
    • 2014-10-08
    • 2020-07-08
    • 1970-01-01
    • 2020-08-22
    相关资源
    最近更新 更多