r - 如何使用 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?
解决方案
推荐阅读
- c# - 远程客户端调用 Dispose() 后仍然能够从 TCPClient 检索 Stream
- c - 通过命令行参数传递特殊字符 Eclipse 与 Visual Studio
- c# - 如何更新 C# Uri 段?
- c# - 在C#中将整数变量除以常数时如何获得双精度值?
- docker - Docker 运行 - 无法在本地找到图像,即使 docker 图像显示它存在
- docker - 将 git commit hash 用于图像标签时设置 k8s 清单图像
- swift - 何时在 swift 块中使用 [self] 与 [weak self]?
- c - 我制作了从一个文件复制数据并使用(读,写)粘贴到另一个文件的程序,但我认为它花费的时间太长
- python - 如何在 PyGame 中拖动多个图像?
- visual-studio - 无法在 Visual Studio 中为终端设置电力线字体