return 时间序列 ts() 对象的开始和结束日期的 R 函数?

R function to return start & end date of a time series ts() object?

我创建了一个包含 300 个时间序列的列表。

现在我想为每个时间序列创建一个训练样本(通过保留最近 3 周)来构建预测模型。 所以我想使用 window 函数对时间序列进行子集化以跳过最近的 3 周,如下所示。

# Creating training data
train_ts<-lapply(ts_list, function(x){
  window(x,start=c(start_year,start_month),end=c(.....,.....))
}
)

但问题是每个时间序列的结束日期都不同。

为了帮助我实现这一点,是否有一个 R 函数可以 return ts 对象的开始值和结束值?

我在这个网站上搜索找不到解决方案。 谢谢

这是一个假设每周数据的简单示例:

x <- ts(rnorm(200), frequency=52)
endx <- end(x)
window(x, end=c(endx[1],endx[2]-3))

当然,一年实际上并没有 52 周,但这可能是大多数分析都可以忽略的并发症。

要获取 ts 对象的开始和结束日期,请使用函数 startend

set.seed(42)

# ts object starting in Jan. 2013 and ending in Dec. 2013
x <- ts(rnorm(12), start = c(2013, 1), end = c(2013, 12), frequency = 12)

start(x)
# [1] 2013    1
end(x)
# [1] 2013   12