我正在使用R中的dLagM包构建一个自回归分布式滞后模型。
管道中的一个步骤是查看用于构建模型的两个时间序列是如何相关的。
我在下面的步骤中使用了建议的代码,但我得到了显示的错误。错误似乎是由于所查看的两个序列不具有相同的属性而导致的。当我在2系列上调用"attribute“时,这些属性似乎是相同的。
我是不是做错了什么?
下面是我的代码:
install.packages(Ecdat)
library(Ecdat)
inflation <- as.numeric(Mishkin[, 1])
inflation_ts <- ts(inflation,start=c(1950,2), frequency = 12)
install.packages("Quandl")
library(Quandl)
Quandl.api_key("ci9fxB")
gdp <- Quandl("FRED/GDP")
gdp <- gdp %>% arrange(-row_number())
gdp <- gdp$Value
gdp_diff <- diff(gdp)
gdp_short <- gdp[1:(length(gdp)-1)]
gdp_change <- (gdp_diff/gdp_short)*100
GDP_mon <- c(sapply(gdp_change, function(gdp_change) c(rep(NA,2),gdp_change)))
GDP_mon <- GDP_mon[2:(length(GDP_mon)-2)]
GDP_mon <- ts(GDP_mon,start=c(1947,1), frequency=12)
GDP_mon <- na_interpolation(GDP_mon, option = "stine")
GDP_mon <- window(GDP_mon,c(1950,2),c(1990,12))
rolCorPlot(y = inflation_ts, x = GDP_mon, width = c(3, 5, 7, 9), level = 0.95,
main = "Rolling correlations between sea levels and temperature",
SDtest = TRUE)
attributes(inflation_ts)
attributes(GDP_mon)发布于 2020-05-26 09:52:34
您正在观察浮点舍入错误,这是由于最初在不同的时间开始,然后对较长的序列进行窗口化以匹配较小的序列而导致的。作为一个更简单的示例(但具有与您的范围匹配的范围),请考虑以下内容(这两个示例都说明了显示相同的神秘不同的时间序列属性,以及一个简单的修复方法):
x <-ts(rnorm(491), start=c(1950,2), frequency = 12)
y <-ts(rnorm(528), start=c(1947,1), frequency = 12)
y <- window(y,c(1950,2),c(1990,12))
print(attributes(x)$tsp) #prints 1950.083 1990.917 12.000
print(attributes(y)$tsp) #prints 1950.083 1990.917 12.000
#but:
print(attributes(x)$tsp == attributes(y)$tsp) #prints TRUE FALSE TRUE (!)
#the fix:
y <- ts(y,start=c(1950,2), frequency = 12)
print(attributes(x)$tsp == attributes(y)$tsp) #prints TRUE TRUE TRUE这里有一些我不明白的奇怪之处。我本以为as.vector(time(x)) (时间序列被采样的时间)本质上与seq(a,b,1/c) (其中attributes(x)$tsp = a b c)相同,但当我将x的时间与seq生成的序列进行比较时,我发现了一个奇怪的差异:
> v <- as.vector(time(x))
> w <- seq(attributes(x)$tsp[1],attributes(x)$tsp[2],1/attributes(x)$tsp[3])
> sum(v == w)
[1] 412
> max(abs(v-w))
[1] 2.273737e-13
> which(v != w)
[1] 255 258 261 264 267 270 273 276 279 282 285 288 291 294 297 300 303 306
[19] 309 312 315 318 321 324 327 330 333 336 339 342 345 348 351 354 357 360
[37] 363 366 369 372 375 378 381 384 387 390 393 396 399 402 405 408 411 414
[55] 417 420 423 426 429 432 435 438 441 444 447 450 453 456 459 462 465 468
[73] 471 474 477 480 483 486 489上面最奇怪的事情是两个向量不同的索引的不连续性质。潜在的问题是1/12不能精确地用浮点数表示,所以v和w都没有它们的点与连续点恰好相差1/12的特性。我的猜测是时间序列对象采用了一种误差减少策略,这会导致不可避免的误差在时间跨度内扩散。由于y和最初的x最初是以不同的起点构建的,所以这个错误的传播方式略有不同,这是window没有修复的。考虑到这些微小差异的非连续性质,我怀疑有时像您的代码一样,将较大的时间序列窗口向下显示为较小的时间跨度,有时会导致时间序列属性完全相等,但其他时间会导致1到2个属性不同,例如2.273737e-13。这可能导致很难跟踪代码似乎可以在测试用例上工作的but,但当输入发生变化时,代码会神秘地崩溃。令我惊讶的是,关于window的文档没有提到这种危险。
https://stackoverflow.com/questions/62012645
复制相似问题