我使用以下内容在大约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值为ts1
和ts2
的ACF。
答案 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])
acf
足以完成工作;设置lag.max = 36
和plot = FALSE
; acf
返回一个列表,我们想要$acf
字段。请注意,这是一个3D arrary,所以我们希望使用c()
将其展平为矢量; [-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)
为什么$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,而不是
ts1
和ts2
。我需要在时间序列的每个滞后时分配。如果你可以解决你的答案非常好。
荣?我误解了你的问题吗?那么,在这种情况下,您只需boxplot
转换acfs
:
boxplot(t(acfs))