使用循环创建时间序列线性模型列表时出错

Error when creating list of time series linear models with a loop

我有以下数据集(代码需要 forecast 包用于 tslm 调用。

x <- rnorm(11, mean = 534, sd = 79)
y <- rnorm(9, mean = 800, sd = 56)
p <- list(x, y) 
tsl <- list(); ts_trend <- list()


for(i in seq_along(p)) {

    tsl[[i]] <- ts(p[[i]], start = c(2018, 1), frequency = 52)
}

    for(i in seq_along(tsl)) {

ts_trend[[i]] <- tslm(tsl[[i]] ~ trend)

}

当我 运行 它时,我收到错误

Error in tsl[[i]] : subscript out of bounds

据我所知,下标显然没有越界。我在之前的循环中使用了相同的引用,没有错误。

我不知道如何解决这个问题。我错过了什么?

我们可以使用 lapply,它会起作用

ts_trendN <- lapply(tsl, function(x) tslm(x ~ trend))

for循环不工作的原因是基于计算trend的环境。我们可以创建一个新环境,它会正常工作

for(i in seq_along(tsl)) {
   ev1 <- new.env()
   ev1$tsl1 <- tsl[[i]]

    ts_trend[[i]] <- tslm(ev1$tsl1 ~ trend)


   }

属性可能有所不同。模型输出相同

library(broom)
identical(tidy(ts_trendN[[1]]), tidy(ts_trend[[1]]))
#[1] TRUE