我有点搞不懂滞后和窗户是怎么工作的。从概念上看,它似乎很简单:延迟基本上是通过“行”数将数据前后移动,而窗口就像一个“select”操作,根据开始和结束时间来指示要使用的数据(据我所理解)。
以下是“用R进行时间序列分析”中的一些代码
library(TSstudio)
data(USVSales)
lags <- function(ts.obj, l) {
ts_merged <- NULL
## Creating n lags
for (i in 1:l) {
## So, for each lag in 1:l, this adds the ts.obj, lagged by i
## to ts_merged, so by the end of this loop we have
## ts(lag=-1), ts(lag=-2) ..., ts(lag=-l)
ts_merged <- ts.union(ts_merged, stats::lag(ts.obj,k=-i))
}
## Merge with the original series (adds the original)
ts_merged <- ts.union(ts.obj,ts_merged)
## set the column names (but how do we know that the first
## 'column' is the original?)
colnames(ts_merged <- c("y",paste0("y_",1:i)))
## Removing NAs as results of lag creation
ts_merged <- window(ts_merged,
start=start(ts.obj)+l,
end=end(ts.obj))
return(ts_merged)
}我制作了两个不同版本的延迟函数,一个基于图书代码(其结果将命名为' book ')另一个相同,但调用window()时注释掉(输出名为'windowless')
书中的例子继续下去..。
> book <- book_lags(USVSales,l=3)
> head(book)
y y_1 y_2 y_3
[1,] 1304.6 1483.8 1148.7 1077.5
[2,] 1373.0 1304.6 1483.8 1148.7
[3,] 1183.8 1373.0 1304.6 1483.8
[4,] 1164.4 1183.8 1373.0 1304.6
[5,] 1207.2 1164.4 1183.8 1373.0
[6,] 1029.6 1207.2 1164.4 1183.8我的代码生成以下内容
> windowless <- windowless_lags(USVSales,l=3)
> head(windowless)
y y_1 y_2 y_3
[1,] 885.2 NA NA NA
[2,] 994.7 885.2 NA NA
[3,] 1243.6 994.7 885.2 NA
[4,] 1191.2 1243.6 994.7 885.2
[5,] 1203.2 1191.2 1243.6 994.7
[6,] 1254.7 1203.2 1191.2 1243.6如果然后将对窗口的调用应用于“无窗口”输出,则得到与书中相同的输出。
head(window(windowless,start=start(windowless)+3,
end=end(windowless)))
y y_1 y_2 y_3
[1,] 1304.6 1483.8 1148.7 1077.5
[2,] 1373.0 1304.6 1483.8 1148.7
[3,] 1183.8 1373.0 1304.6 1483.8
[4,] 1164.4 1183.8 1373.0 1304.6
[5,] 1207.2 1164.4 1183.8 1373.0
[6,] 1029.6 1207.2 1164.4 1183.8我不明白为什么第一排“(头(没有窗户),.”不等于“无窗口”的第四行。1304.6是从哪里来的?
我遗漏了什么?
发布于 2022-09-19 15:49:50
神秘的是,window()中的‘`start’关键字可以给出一个数字,但是(在本例中)它被解释为,是年增量和月增量。
> foo <- ts(data=1:60,frequency=12)
> ts_info(foo)
The foo series is a ts object with 1 variable and 60 observations
Frequency: 12
Start time: 1 1
End time: 5 12
> bar <- window(foo,start=start(foo)+3,end=end(foo))
> ts_info(bar)
The bar series is a ts object with 1 variable and 21 observations
Frequency: 12
Start time: 4 4
End time: 5 12 “1304.6”来自于USVSales ts对象第三年的第三个月
> ts_info(USVSales)
The USVSales series is a ts object with 1 variable and 528 observations
Frequency: 12
Start time: 1976 1
End time: 2019 12
> baz <- window(USVSales,start=start(USVSales)+3,end=start(USVSales)+6)
> ts_info(baz)
The baz series is a ts object with 1 variable and 40 observations
Frequency: 12
Start time: 1979 4
End time: 1982 7
>
head(baz,1)
[1] 1304.6https://stackoverflow.com/questions/73755583
复制相似问题