## In these examples, 'nsim' is 1E4 or 1E5 to save
## Rcmd check time (CRAN). It is advocated
## to use at least 'nsim = 1E6' though...
## Example from ?nls.
DNase1 <- subset(DNase, Run == 1)
fm3DNase1 <- nls(density ~ Asym/(1 + exp((xmid - log(conc))/scal)),
data = DNase1, start = list(Asym = 3, xmid = 0, scal = 1))
## Using a single predictor value without error.
PROP1 <- predictNLS(fm3DNase1, newdata = data.frame(conc = 2), nsim = 10000)
PRED1 <- predict(fm3DNase1, newdata = data.frame(conc = 2))
PROP1$summary
PRED1
## => mean.1 equal to PRED1
## Using a single predictor value with error.
PROP2 <- predictNLS(fm3DNase1, newdata = data.frame(conc = 2),
newerror = data.frame(conc = 0.5), nsim = 10000)
PROP2$summary
## Two predictors with correlated errors (r = 0.9)
set.seed(1); x <- runif(30, 1, 10); z <- runif(30, 0, 2)
y <- 5 * exp(-0.3 * x) + 2 * z^1.5 + rnorm(30, 0, 0.05)
fm2 <- nls(y ~ a * exp(-b * x) + g * z^d, start = list(a = 4, b = 0.2, g = 1, d = 1))
S <- matrix(c(0.2^2, 0.9 * 0.2 * 0.05, 0.9 * 0.2 * 0.05, 0.05^2), 2,
dimnames = list(c("x", "z"), c("x", "z")))
## 'S' is a covariance matrix (variances, not standard uncertainties)
## whose dimnames are the predictor names.
predictNLS(fm2, newdata = data.frame(x = 5, z = 1), newerror = S, nsim = 1E4)$summary
## A list of covariance matrices, one per row of 'newdata'.
predictNLS(fm2, newdata = data.frame(x = c(5, 6), z = c(1, 1)),
newerror = list(S, 2 * S), nsim = 1E4)$summary
# \donttest{
## Using a sequence of predictor values without error.
CONC <- seq(1, 12, by = 1)
PROP3 <- predictNLS(fm3DNase1, newdata = data.frame(conc = CONC), nsim = 10000)
PRED3 <- predict(fm3DNase1, newdata = data.frame(conc = CONC))
PROP3$summary
PRED3
## => mean.1 equal to PRED3
## Plot mean and confidence values from first-/second-order
## Taylor expansion and Monte Carlo simulation.
plot(DNase1$conc, DNase1$density)
lines(DNase1$conc, fitted(fm3DNase1), lwd = 2, col = 1)
points(CONC, PROP3$summary[, 1], col = 2, pch = 16)
lines(CONC, PROP3$summary[, 5], col = 2)
lines(CONC, PROP3$summary[, 6], col = 2)
lines(CONC, PROP3$summary[, 11], col = 4)
lines(CONC, PROP3$summary[, 12], col = 4)
# }
## Gauge: for a model that is linear in the coefficients,
## the Taylor and Monte Carlo intervals equal those of predict.lm.
set.seed(70)
xx <- 1:15
yy <- 2 + 0.5 * xx + rnorm(15, 0, 0.4)
fitN <- nls(yy ~ a + b * xx, start = list(a = 1, b = 1))
fitL <- lm(yy ~ xx)
PN <- predictNLS(fitN, newdata = data.frame(xx = 7.3), interval = "prediction", nsim = 1E5)
PN$summary[, c(5, 6, 11, 12)]
predict(fitL, newdata = data.frame(xx = 7.3), interval = "prediction")
## => Taylor interval (columns 5, 6) equal to lwr/upr (4.806, 6.373),
## Monte Carlo interval (columns 11, 12) within the Monte Carlo error
Run the code above in your browser using DataLab