add_ci: Add Confidence Intervals for Fitted Values to Data Frames

Description Usage Arguments Details Value See Also Examples

View source: R/add_ci.R

Description

This is a generic function to append confidence intervals for predictions of a model fit to a data frame. A confidence interval is generated for the fitted value of each observation in df. These confidence intervals are then appended to df and returned to the user as a data frame. The fit may be a linear, log-linear, linear mixed, generalized linear model, generalized linear mixed, or accelerated failure time model.

Usage

1
add_ci(df, fit, alpha = 0.05, names = NULL, yhatName = "pred", ...)

Arguments

df

A data frame of new data. df can be the original data or new data.

fit

An object of class lm, glm, lmerMod, glmerMod, or survreg. Predictions are made with this object.

alpha

A real number between 0 and 1. Controls the confidence level of the interval estimates.

names

NULL or character vector of length two. If NULL, confidence bounds automatically will be named by add_ci, otherwise, the lower confidence bound will be named names[1] and the upper confidence bound will be named names[2].

yhatName

A character vector of length one. Name of the vector of the predictions made for each observation in df

...

Additional arguments.

Details

For more specific information about the arguments that are applicable in each method, consult:

Note that add_ci calculates confidence intervals for fitted values, not model coefficients. For confidence intervals of model coefficients, see confint.

Value

A dataframe, df, with predicted values, upper and lower confidence bounds attached.

See Also

add_pi for prediction intervals, add_probs for response level probabilities, and add_quantile for quantiles of the conditional response distribution.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Fit a linear model
fit <- lm(dist ~ speed, data = cars)
# Make a confidence interval for each observation in cars, and
# append to the data frame
add_ci(cars, fit)

# Make new data
new_data <- cars[sample(NROW(cars), 10), ]
add_ci(new_data, fit)

# Fit a Poisson model
fit2 <- glm(dist ~ speed, family = "poisson", data = cars)
# Append CIs
add_ci(cars, fit2)

# Fit a linear mixed model using lme4
fit3 <- lme4::lmer(Reaction ~ Days + (1|Subject), data = lme4::sleepstudy)
# Append CIs
# Generally, you should use more than 100 bootstrap replicates
add_ci(lme4::sleepstudy, fit3, nSims = 100)

# Fit a logistic model
fit4 <- glm(I(dist > 20) ~ speed, family = "binomial", data = cars)
# Append CIs
add_ci(cbind(cars, I(cars$dist > 20)), fit4)

ciTools documentation built on Jan. 13, 2021, 7 a.m.