Mobeus Zoom
Mobeus Zoom

Reputation: 608

R time-series prediction with linear model

I have an XTS dataframe where I am trying to fit a linear model to a set of future dates. I have divided the dataframe into a past and present (for other reasons) and I fit the linear model as follows

lin_mod <- lm(PastExchg ~ Time, data = BackDF)

That's fine. But when I try to make predictions using predict on the Time column for the future data, I get an error

ForwDF$pred <- predict(lin_mod, newdata= ForwDF$Time)

I suspect this may have something to do with the fact that the Time column is in Date format. Or perhaps that the Time column is irregular. How can I fix this?

ForwDF looks like

              PLN       Time
2004-06-28 4.5331 2004-06-28
2004-06-29 4.5270 2004-06-29
2004-06-30 4.5025 2004-06-30
2004-07-01 4.5155 2004-07-01
2004-07-02 4.5258 2004-07-02
2004-07-05 4.5304 2004-07-05
2004-07-06 4.5138 2004-07-06
2004-07-07 4.5330 2004-07-07

PLN is the true value of the column (which I will compare the predictions in pred against later--once I can get them!!).

Upvotes: 2

Views: 848

Answers (2)

Elias
Elias

Reputation: 736

Try this:

ForwDF$pred <- predict(lin_mod, newdata= data.frame(Time = ForwDF$Time))

Let me know if it worked.

Edit: See the comment of Jason, for the explenation why your solution did not work.

Upvotes: 3

Anders Ellern Bilgrau
Anders Ellern Bilgrau

Reputation: 10223

This works:

# Create similar data
Time <- sort(sample(seq(Sys.Date(), Sys.Date() - 200, length.out = 200))[1:100])
df <- data.frame(y = rnorm(100), Time = Time)

# Linear regression and prediction
lin_mod <- lm(y ~ Time, data = df)
df$pred <- predict(lin_mod, newdata=list(Time = df$Time)

Upvotes: 0

Related Questions