Search code examples
rdatemachine-learningprediction

how to predict value for future date in r


sample data ->

> tail(India_df)
          date confirmed deaths recovered
98  2020-04-28     31324   1008      7747
99  2020-04-29     33062   1079      8437
100 2020-04-30     34863   1154      9068
101 2020-05-01     37257   1223     10007
102 2020-05-02     39699   1323     10819
103 2020-05-03     42505   1391     11775

i want to predict that how many confirmed cases will be there on some future date like -> "2020-05-05"

i am using polynomial regression to fit the model ->

fit2 = lm(confirmed~poly(date,6))

i tried using this ->

new <- data.frame(pred_dates <- as.Date(c("2020-05-05","2020-05-06")))
predict.lm(fit2,new,interval = "confidence")

but it is showing this error ->

'newdata' had 2 rows but variables found have 103 rows 

Solution

  • You have to use the data argument in lm, and use the same names of the predictors in the new dataframe:

    fit2 <- lm(confirmed ~ poly(date,6), data = India_df)
    
    new <- data.frame(date = as.Date(c("2020-05-05","2020-05-06")))
    
    predict(fit2, new, interval = "confidence")