首页 > 解决方案 > 如何使用 R 中的 astsa 包在 lag2.plot() 中指定滞后值

问题描述

我有一个包含三列的示例表:两个变量值,以及它们被记录的时间:使用 ccf() 函数作为 R 中 asta 包的一部分,我可以获得具有正负滞后值的相关值的数据框。但是,使用 lag2.plot() 创建散点图时,我只能绘制负滞后值。我有两个问题: 1. 有没有办法绘制正滞后值?2. 如果我对特定的滞后值感兴趣(例如 lag = 3),有没有办法在 lag2.plot() 中仅绘制这个滞后值?看来我只能指定最大滞后。

以下是可重现的代码:

#import astsa package
library(astsa)

#Create sample table: 

Date<- c("2019-11-11 00:00:00", "2019-11-11 00:30:00", "2019-11-11 01:00:00", "2019-11-11 01:30:00",
       "2019-11-11 02:00:00", "2019-11-11 02:30:00", "2019-11-11 03:00:00", "2019-11-11 03:30:00",
       "2019-11-11 04:00:00", "2019-11-11 04:30:00", "2019-11-11 05:00:00")

Var1<- c(7.061299, 7.317042, 7.141096, 8.324985, 8.476613, 8.530634, 9.095559, 8.240867, 8.120649, 9.682123,
        9.048403)

Var2<- c(-2.53624, -2.39976, -2.44062, -2.13758, -2.46917, -2.74427, -2.36640, -2.02009, -3.36604, -1.91474,
       -2.14645)

tb1<- data.frame(Date, Var1, Var2)

#convert data to time series
tb1_ts<- as.ts(tb1)

#Detrend data via 1st differencing
tb1_dif <- diff(tb1_ts, lag = 1, differences = 1)

#Cross correlation ccf() function. 
tb1_ccf <- ccf(tb1_dif[,"Var1"], tb1_dif[,"Var2"], lag.max=48, type = c("correlation"))

#Create a dataframe of correlation/lag values from ccf() function output, rename columns accordingly
#and cbind into table
tb1_cor<- as.data.frame(tb1_ccf$acf)
colnames(tb1_cor)<- "Correlation"
tb1_lag<- as.data.frame(tb1_ccf$lag)
colnames(tb1_lag)<- "Lag"
tb_bind<- cbind(tb1_cor, tb1_lag)

#Subset table with correlation/lag values to only lag values = +/- 4 
tb_bind1<- tb_bind[tb_bind$Lag>= -4 & tb_bind$Lag <= 4,]

#Inspect the table, notice the Lag ranges from -4 to +4, resulting in 9 correlation values
tb_bind1

#Use lag2.plot to plot data with a max.lag of 4, inclusion of correlation values set to TRUE.
#Notice only negative lag values are plotted (the correlation values are rounded off)
lag2.plot(tb1_dif[,"Var1"], tb1_dif[,"Var2"], max.lag = 4, corr = TRUE, smooth = FALSE)

如何修改此代码,以便绘图中包含正的 Lag 值?此外,如何修改它以便仅绘制 Lag = 3?

标签: rtime-series

解决方案


推荐阅读