生成用于多个ACF的箱线图 [英] Produce a boxplot for multiple ACFs

查看:127
本文介绍了生成用于多个ACF的箱线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下命令在大约200列上运行 forecast :: Acf 。现在,我想生成一个箱形图,显示滞后1:36时相关值的分布。

I used the following to run forecast::Acf over about 200 columns. Now I would like to generate a boxplot showing the distribution of correlation values at lag 1:36.

## a simple example
d <- data.frame(ts1 = rnorm(100), ts2 = rnorm(100))
acorr <- apply(d, 2, Acf)

我现在想要的是一个箱形图,其中x值为1,2,y值为ACF, ts1 ts2

What I now want is a boxplot where x-values are 1,2 and the y-values are ACF for ts1 and ts2.

推荐答案

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

Suppose you have multiple time series stored in a data frame d (each column is one series), we can use the following to obtain ACF up to lag 36 (nrow(d) >> 36 to make sense!):

## for data frame `d`
acfs <- sapply(d, function (u) c(acf(u, lag.max = 36, plot = FALSE)$acf)[-1])




  • R基本函数 acf 工作;设置 lag.max = 36 plot = FALSE ;

  • acf 返回一个列表,我们想要 $ acf 字段。请注意,这是一个3D光栅,因此我们想使用 c();

  • ACF滞后0将其展平为向量是1并且不感兴趣,因此我们将其删除 [-1] ;

  • sapply 将返回一个矩阵,每一列为每个序列提供ACF。

    • R base function acf is sufficient for the job; set lag.max = 36 and plot = FALSE;
    • acf returns a list, and we want $acf field. Note, this is a 3D arrary, so we want to flatten it into a vector using c();
    • ACF at lag 0 is 1 and is not of interest, so we drop it by [-1];
    • sapply would return a matrix, each column giving ACF for each series.
    • 如果您将时间序列存储在矩阵(普通矩阵或带有 mts类的矩阵),我们使用 apply 而不是 sapply

      In case you have time series stored in a matrix (either an ordinary matrix or one with "mts" class), we use apply rather than sapply:

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

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

      To produce a boxplot, simply use:

      boxplot(acfs)
      

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

      Why is $acf a 3D array. Because acf function can handle multiple time series directly. Try:

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

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

      The problem is, in this case, cross-correlation (CCF) is also computed.


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

      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.

      Ei?我读错了你的问题吗?好吧,在那种情况下,您只需 boxplot acfs 的转置:

      Ei? Did I misread your question. Well, in that case, you just boxplot the transpose of acfs:

      boxplot(t(acfs))
      

      这篇关于生成用于多个ACF的箱线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆