1

I have the following data set (code requires the forecast package for the tslm call.

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)

}

When I run it, I get the error

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

The subscript, to my knowledge, is clearly not out of bounds. I use the same reference in the prior loop, with no error.

I have no idea how to fix this. What am I missing?

4

1 回答 1

0

我们可以使用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
于 2018-08-11T13:51:16.353 回答