l_predict: Model Prediction

View source: R/l_predict.R

l_predictR Documentation

Model Prediction

Description

It is entirely for the purpose of plotting fits and intervals on a scatterplot (or histogram). It is a generic function to predict models for loon smooth layer (a wrap of the function predict). However, the output is unified.

Usage

l_predict(model, ...)

## Default S3 method:
l_predict(model, ...)

## S3 method for class 'lm'
l_predict(
  model,
  newdata = NULL,
  interval = c("none", "confidence", "prediction"),
  level = 0.95,
  ...
)

## S3 method for class 'nls'
l_predict(
  model,
  newdata = NULL,
  interval = c("none", "confidence", "prediction"),
  level = 0.95,
  ...
)

## S3 method for class 'glm'
l_predict(
  model,
  newdata = NULL,
  interval = c("none", "confidence"),
  level = 0.95,
  ...
)

## S3 method for class 'loess'
l_predict(
  model,
  newdata = NULL,
  interval = c("none", "confidence", "prediction"),
  level = 0.95,
  ...
)

Arguments

model

a model object for which prediction is desired

...

arguments passed in predict

newdata

optionally, a data frame in which to look for variables with which to predict. If omitted, the fitted linear predictors are used.

interval

type of interval, could be "none", "confidence" or "prediction" (not for glm)

level

confidence level

Value

A data frame is returned with x (if newdata is given) and y. If the interval is not none, two more columns, lower (lower interval) and upper (upper interval) will be returned.

Examples

y <- rnorm(10)
x <- rnorm(10)
model1 <- lm(y ~ x)
# formal output
pre <- l_predict(model1, newdata = data.frame(x = sort(x)),
                 interval = "conf")
head(pre)

if(interactive()) {
p <- with(cars, l_plot(speed, dist))

# Example taken from
# https://stackoverflow.com/questions/23852505/how-to-get-confidence-interval-for-smooth-spline
#
l_predict.smooth.spline <- function(model, interval = c("confidence", "none"),
                                    level = 0.95, ...) {
# confidence interval of `smooth.spline`
  interval <- match.arg(interval)

  res <- (model$yin - model$y)/(1 - model$lev)     # jackknife residuals
  sigma <- sqrt(var(res))                          # estimate sd
  std <- stats::qnorm(level / 2 + 0.5)
  upper <- model$y + std * sigma * sqrt(model$lev) # upper 95% conf. band
  lower <- model$y - std * sigma * sqrt(model$lev) # lower 95% conf. band

  data.frame(y = model$yin, lower = lower, upper = upper)
}
l <- l_layer_smooth(p, method = "smooth.spline", interval = "confidence")
}


loon documentation built on July 9, 2023, 5:48 p.m.