1
votes

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?

1
You have two for loops. i think the nested is not needed. for(i in seq_along(tsl)) ts_trend[[i]] <- tslm(tsl[[i]] ~ trend)akrun
You can actually combine both for one for loop. What is trend?Parfait
sorry @akrun that was a typo error which I've fixed. @Parfait trend is an argument only for the tslm call. You can call trend and the coef will be the linear trend for the time series object. You can also construct the call tslm(x ~ trend + season) and season will product seasonality coefficients as well as trend.Todd Shannon

1 Answers

0
votes

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