0

I have one data frame, which is composed of three columns(PIT,CIT and VAT). My intention is to make forecast with each of this three times series with Forecast package. For that reason I convert data frame into ts object.

Now I want to make forecasting with snaive function which is part from Forecast package.So I wrote this lines of code:

  SNAIVE_PIT<-snaive(TS_REVENUES[, 'PIT'],h=5) 
  SNAIVE_CIT<-snaive(TS_REVENUES[, 'CIT'],h=5) 
  SNAIVE_VAT<-snaive(TS_REVENUES[, 'VAT'],h=5)

But my intention is to simplify this code with some function like: loop,for or other function, which can automatically calculate forecasting for each of this three times series(PIT,CIT and VAT) ? I am asking this because this time series is only small part of whole series and I must to simplify this forecasting procedures.

#CODE

library(forecast)

  # Making data frame 
   DATA_SET<-data.frame(
                    PIT=seq(1, 48, by = 2),
                    CIT=seq(1, 24, by = 1),
                    VAT=seq(1, 94, by = 4)
                    )
     View(DATA_SET)

    # Making TS object
      TS_REVENUES<-ts(DATA_SET,start=c(2016,1),frequency = 12)

    # Extracting column names from TS object
      COL_NAMES_TS<-TS_REVENUES[0:0,]
      COL_NAMES_TS

    # Making forecasting with Forecast package      
      SNAIVE_PIT<-snaive(TS_REVENUES[, 'PIT'],h=5) 
      SNAIVE_CIT<-snaive(TS_REVENUES[, 'CIT'],h=5) 
      SNAIVE_VAT<-snaive(TS_REVENUES[, 'VAT'],h=5) 

1 Answer 1

1

If I understand you correctly, then you want to cycle through each column in your dataframe and forecast from it. If so, I think the code below will help.

library(forecast)

# Making data frame 
DATA_SET<-data.frame(
  PIT=seq(1, 48, by = 2),
  CIT=seq(1, 24, by = 1),
  VAT=seq(1, 94, by = 4)
)
View(DATA_SET)

for(i in 1:ncol(DATA_SET)){
  # Build a ts for this column
  timeseries <- ts(DATA_SET[,i], start=c(2016,1), frequency = 12)
  # Build a foreacst based on the ts
  forecast <- snaive(timeseries,h=5)

  # rename the forecast according to the original variable name
  colname <- colnames(DATA_SET)[i]
  forecastName <- paste("SNAIVE_",colname," <- forecast",sep="")
  eval(parse(text = forecastName))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.