library(DImodels)
data(sim1)
# Fit a model
mod <- lm(response ~ 0 + p1 + p2 + p3 + p4 + p1:p2 + p3:p4, data = sim1)
# Create new data for adding predictions
newdata <- head(sim1[sim1$block == 1,])
print(newdata)
# Add predictions to data
add_prediction(data = newdata, model = mod)
# Adding predictions to data with confidence interval
add_prediction(data = newdata, model = mod, interval = "confidence")
# Calculate prediction intervals instead
add_prediction(data = newdata, model = mod, interval = "prediction")
# Default is a 95% interval, change to 99%
add_prediction(data = newdata, model = mod, interval = "prediction",
conf.level = 0.99)
####################################################################
##### Use model coefficients for prediction
coeffs <- mod$coefficients
# Would now have to add columns corresponding to each coefficient in the
# data and ensure there is an appropriate mapping between data columns and
# the coefficients.
newdata$`p1:p2` = newdata$p1 * newdata$p2
newdata$`p3:p4` = newdata$p3 * newdata$p4
# If the coefficients are named then the function will try to
# perform matching between data columns and the coefficients
# Notice that confidence intervals are not produced if we don't
# specify a variance covariance matrix
add_prediction(data = newdata, coefficients = coeffs)
# However, if the coefficients are not named
# The user would have to manually specify the subset
# of data columns arranged according to the coefficients
coeffs <- unname(coeffs)
subset_data <- newdata[, c(3:6, 8,9)]
subset_data # Notice now we have the exact columns in data as in coefficients
add_prediction(data = subset_data, coefficients = coeffs)
# Or specify a selection (either by name or index) in coeff_cols
add_prediction(data = newdata, coefficients = coeffs,
coeff_cols = c("p1", "p2", "p3", "p4", "p1:p2", "p3:p4"))
add_prediction(data = newdata, coefficients = coeffs,
coeff_cols = c(3, 4, 5, 6, 8, 9))
# Adding confidence intervals when using model coefficients
coeffs <- mod$coefficients
# We need to provide a variance-covariance matrix to calculate the CI
# when using `coefficients` argument. The following warning will be given
add_prediction(data = newdata, coefficients = coeffs,
interval = "confidence")
vcov_mat <- vcov(mod)
add_prediction(data = newdata, coefficients = coeffs,
interval = "confidence", vcov = vcov_mat)
# Currently both confidence and prediction intervals will be the same when
# using this method
add_prediction(data = newdata, coefficients = coeffs,
interval = "prediction", vcov = vcov_mat)
Run the code above in your browser using DataLab