Search code examples
rfor-loopforecast

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


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?


Solution

  • We can use lapply and it would work

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

    The reason why for loop is not working is based on the environment on which trend is calculated. We can create a new environment and it would work fine

    for(i in seq_along(tsl)) {
       ev1 <- new.env()
       ev1$tsl1 <- tsl[[i]]
    
        ts_trend[[i]] <- tslm(ev1$tsl1 ~ trend)
    
    
       }
    

    There may be some difference in attributes. The model output is the same

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