总结来自ts(rnorm)对象的月度(季节性)因素

时间:2015-04-02 00:42:15

标签: r time-series dplyr summary

我正在尝试使用dplyr和ts包创建每月因子变量。

这意味着:

  1. 取Y年的平均值
  2. 总结所有^ 1(十二,每月一个)
  3. 每个月将1除以2< - 这是您当月的因素。
  4. 所以,如果每个月得到它的数值,March的因子就是

      

    3 /总和(1:12)   [1] 0.03846154

    或3.8%。

    我觉得这应该是非常直接的,但我搞砸了,不知道为什么(也许是中期):

    x <- ts(matrix(rnorm(300,100,3)), start = c(1961,1), frequency = 12) y 
    y <- x  %>% summarise(month_factor = for (i in z) mean(i)) 
    Error in UseMethod("summarise_") :    no applicable method for 'summarise_' applied to an object of class "ts"
    

    我知道第一次努力是非常不合格的,但我遇到了无法使用mutate的复合问题,因为月份是我在上面构建的ts对象x中的列

1 个答案:

答案 0 :(得分:1)

例如:

x <- ts(matrix(rnorm(300,100,3)), start = c(1961,1), frequency = 12) 

根据BondedDust的建议,您可以将x转换为矩阵:

m <- matrix(data = as.numeric(x), ncol = 12, byrow = TRUE)

按季节平均值调整:

m = m/matrix(colMeans(m, na.rm = TRUE), ncol = 12, nrow=nrow(m), byrow = TRUE)

转换回ts

y = ts(data = as.numeric(m), start = start(x), frequency = 12)