为多个 ACF 生成箱线图

Produce a boxplot for multiple ACFs

我将以下内容用于 运行 forecast::Acf 大约 200 列。现在我想生成一个箱线图,显示延迟 1:36.

时相关值的分布
## a simple example
d <- data.frame(ts1 = rnorm(100), ts2 = rnorm(100))
acorr <- apply(d, 2, Acf)

我现在想要的是一个箱线图,其中 x 值为 1,2,y 值为 ts1ts2 的 ACF。

假设你有多个时间序列存储在一个数据框中d(每列是一个系列),我们可以使用以下方法获得最大滞后 36 的 ACF(nrow(d) >> 36 有意义!):

## for data frame `d`
acfs <- sapply(d, function (u) c(acf(u, lag.max = 36, plot = FALSE)$acf)[-1])
  • R 基本函数 acf 足以完成工作;设置 lag.max = 36plot = FALSE
  • acf return 是一个列表,我们需要 $acf 字段。请注意,这是一个 3D 数组,因此我们想使用 c();
  • 将其展平为向量
  • 滞后 0 处的 ACF 为 1,我们不感兴趣,因此我们将其降低 [-1]
  • sapply 会 return 一个矩阵,每一列给出每个系列的 ACF。

如果您将时间序列存储在矩阵中(普通矩阵或具有 "mts" class 的矩阵),我们使用 apply 而不是 sapply

## for matrix `d`
acfs <- apply(d, 2L, function (u) c(acf(u, lag.max = 36, plot = FALSE)$acf)[-1])

要生成箱线图,只需使用:

boxplot(acfs)


为什么 $acf 是一个 3D 数组。因为 acf 函数可以直接处理多个时间序列。尝试:

## whether `d` is data frame or matrix, it is converted to "mts" inside `acf`
oo <- acf(d, lag.max = 36, plot = FALSE)$acf

问题是,在这种情况下,还会计算互相关 (CCF)。


On the x-axis I want 1-36, not ts1 and ts2. I need the distribution of at each lag over time series. If you can fix that your answer is very good.

诶?我是不是看错了你的问题。那么,在这种情况下,您只需 boxplot acfs:

的转置
boxplot(t(acfs))