Search code examples
rforecasting

Linear regression Forecasting in R


Having trouble scripting my forecast in R. I have all my time series data in a .csv document that is imported to the global environment. The code works all the way down to anova(reg1). So my question is really why the rest of the script doesn't work, and how do I need to edit the script to make it look something like example 4.4 looks like in this link(https://www.otexts.org/fpp/4/8)

data <- read.csv("Ny.csv", h=T, sep=";")

SeasonallyadjustedStockprice<-data$Seasonallyadj

Oilprice<-data$Oilaverage

Index<-data$DJI

plot.ts(Oilprice)

plot.ts(SeasonallyadjustedStockprice)

plot.ts(Index)

reg1<-lm(SeasonallyadjustedStockprice~Oilprice+Index)

summary(reg1)

anova(reg1)

Time <- tslm(SeasonallyadjustedStockprice~Oilprice+Index) 

f <- forecast(Time, h=5,level=c(80,95))

The error message is the following: Error in tslm(SeasonallyadjustedStockprice ~ Oilprice + Index) : Not time series data


Solution

  • It looks like its because the terms on the right side of the formula are not time series. Here is a simplified example:

    >df
      a b
    1 1 2
    2 2 4
    3 3 6
    4 4 8
    
    > y
    [1] 1 3 5 7
    
    >tslm(y ~ a + b, data=df)
    Error in tslm(y ~ a + b, data = df) : Not time series data
    
    > dfts = ts(df)    # This is of class 'mts' (multiple time series)
    > tslm(y ~ a + b, data=dfts)
    
    Call:
    lm(formula = formula, data = dfts, na.action = na.exclude)
    
    Coefficients:
    (Intercept)            a            b  
             -1            2           NA  
    

    Which is basically sane output for this overly simplified example.