从 ts(rnorm) 对象中汇总每月(季节性)因素

Summarise monthly (seasonal) factors from an ts(rnorm) object

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

这意味着:

  1. 取 Y 年月数的平均值
  2. 对所有 ^1 求和(十二个,每个月一个)
  3. 每个月用 1 除以 2 <- 这是你当月的因数。

因此,如果每个月都得到它的数值,则三月的因子将为

3/sum(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 我在上面建造。

例如:

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)