Vinicius Soares
Vinicius Soares

Reputation: 149

how to apply a function on a list and return a vector?R

I am trying to create a vector with the sum of the forecasts created but the vector is only storing the last value, how to create a vector with each sum?

library(forecast)

setwd("C:\\Users\\Note\\Documents\\Ssl")
n <- dir(pattern = ".csv")
forecastOut <- lapply(n, function(x) {
  dat <- read.csv(x, sep=";", header = TRUE)
  predic <- auto.arima(dat[,1])
  forecast(predic, h = 4)
    }) 

names(forecastOut) <- n

for (i in forecastOut){
  sum<-c(sum(unlist((i[4]))))
 }   
>sum
[1] 2944.32
> class(forecastOut)
[1] "list"

Upvotes: 1

Views: 37

Answers (1)

akrun
akrun

Reputation: 886938

We can create sum initialized as a vector

Sum <- numeric(length(forecatsOut))
for(i in seq_along(forecastOut)) {
    Sum[i] <- sum(forecastOut[[4]], na.rm = TRUE)
 }

Or append the output with c()

Sum <- c()
for(out in forecastOut) {
    Sum <- c(Sum, sum(out[[4]]))
 }

In the OP's loop, the sum is getting updated in each iteration and returns the last sum value

Upvotes: 1

Related Questions