FMM
FMM

Reputation: 2005

How to calculate 95% prediction interval from nls

Borrowing the example data from this question, if I have the following data and I fit the following non linear model to it, how can I calculate the 95% prediction interval for my curve?

library(broom)
library(tidyverse)

x <- seq(0, 4, 0.1)
y1 <- (x * 2 / (0.2 + x))
y <- y1 + rnorm(length(y1), 0, 0.2)

d <- data.frame(x, y)

mymodel <- nls(y ~ v * x / (k + x),
            start = list(v = 1.9, k = 0.19),
            data = d)

mymodel_aug <- augment(mymodel)

ggplot(mymodel_aug, aes(x, y)) +
  geom_point() +
  geom_line(aes(y = .fitted), color = "red") +
  theme_minimal()

enter image description here

As an example, I can easily calculate the prediction interval from a linear model like this:

## linear example

d2 <- d %>%
  filter(x > 1)

mylinear <- lm(y ~ x, data = d2)

mypredictions <-
  predict(mylinear, interval = "prediction", level = 0.95) %>%
  as_tibble()

d3 <- bind_cols(d2, mypredictions)

ggplot(d3, aes(x, y)) +
  geom_point() +
  geom_line(aes(y = fit)) +
  geom_ribbon(aes(ymin = lwr, ymax = upr), alpha = .15) +
  theme_minimal()

enter image description here

Upvotes: 4

Views: 3484

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226047

Based on the linked question, it looks like the investr::predFit function will do what you want.

investr::predFit(mymodel,interval="prediction")

?predFit doesn't explain how the intervals are computed, but ?plotFit says:

Confidence/prediction bands for nonlinear regression (i.e., objects of class ‘nls’) are based on a linear approximation as described in Bates & Watts (2007). This fun[c]tion was in[s]pired by the ‘plotfit’ function from the ‘nlstools’ package.

also known as the Delta method (e.g. see emdbook::deltavar).

Upvotes: 6

Related Questions