为多个ACF生成箱线图

时间:2016-12-10 21:36:39

标签: r plot time-series boxplot

我使用以下内容在大约200列上运行forecast::Acf。现在我想生成一个箱线图,显示滞后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。

1 个答案:

答案 0 :(得分:2)

假设您有多个时间序列存储在数据框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返回一个列表,我们想要$acf字段。请注意,这是一个3D arrary,所以我们希望使用c()将其展平为矢量;
  • 滞后0处的ACF为1且不感兴趣,因此我们将其降低[-1];
  • sapply将返回一个矩阵,每列为每个系列提供ACF。

如果您将时间序列存储在矩阵中(普通矩阵或带有&#34; mts&#34;类的矩阵),我们使用apply而不是sapply

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

要制作箱线图,只需使用:

boxplot(acfs)

boxplot

为什么$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)。

  

在x轴上,我想要1-36,而不是ts1ts2。我需要在时间序列的每个滞后时分配。如果你可以解决你的答案非常好。

荣?我误解了你的问题吗?那么,在这种情况下,您只需boxplot转换acfs

boxplot(t(acfs))

trans