rregressionpredictiondata-fitting

How can I find the date for which a model predicts a specified value?


I have data that consists of values on dates, e.g.

Date       Value
2024-02-12 7
2024-02-13 8
2024-02-14 9

I have fit a model to that data and can now calculate the predicted values for a future date:

dat <-  read.table(textConnection("
Date Value
2024-02-12 7
2024-02-13 8
2024-02-14 9
2024-04-20 NA
"), header = TRUE, colClasses = c("Date", "integer"))
model <- glm(Value ~ Date, data = dat)
prediction <- predict(model, dat)

In this way I can find the predicted value for one single specific date.

But what if I want to find the date for which specific value is predicted?

My solution has been to caculate the predicted values for a long period of time into the future and then search the predicted values to find the corresponding date. This approach often necessitates long sequences and large datasets and long calculation times.

For example, for the sample data above, it would be difficult for me to eyeball on what exact date the value would be 75. I would therefore calculate all values for the next couple of months and then sift through the predicted values to find the date that goes with the value 75.

Is there a more efficient method to find that date directly, without having to calculate a series of values?

For the above example, the model predicts the value 75 for 2024-02-20. What if I didn't know this and wanted to find the date for which the model predicts the value 75 without calculating all values for the next upcoming months?


I have asked a follow-up question here: How can I find the date for which a model from family = poisson(link = "log") predicts a specified value?


Solution

  • You can rearrange your model equation to calculate this:

    # Extract the coefficient of the model you've built
    coef <- coef(model)
    
    # Calculate the date for your specific value (in this case 75)
    result <- (75 - coef[1]) / coef[2]
    

    You may need to convert the numeric answer to a date. e.g.

    as.Date(result , origin = "1970-01-01")