create_prediction_data: Generate prediction data

Description Usage Arguments Details Value Examples

View source: R/create_prediction_data.R

Description

Straightforward way to quickly create data to make model predictions.

Usage

1
2
3
4
5
6
7
create_prediction_data(
  model_data,
  conditional_data = NULL,
  num = mean,
  cat = "most_common",
  ...
)

Arguments

model_data

The original data. Ideally this would come from a model object.

conditional_data

A data.frame constructed from something like base::expand.grid

num

A function like mean or median to be applied to numeric data. Should return a single value. Default is mean.

cat

Set categorical variables to the reference level ('ref') or the most frequently occurring category (most_common, the default).

...

Additional arguments to num, e.g. na.rm=T

Details

Given data that was used in a model, create data that can be used for predictions at key values, especially as a prelude to visualization. Some package functions can be found that do this, but are specific to certain models or don't quite provide the flexibility I want. Specifically, this allows for an arbitrary function to apply to numeric variables, and for categorical(ish) variables, one has the option for the most common category (ties go to the first category), or the reference level if a factor. For now class Date is treated as categorical.

In addition, one may supply their own data to set certain variables at any particular values via the conditional_data argument, for example, using expand.grid or tidyr::crossing. Variables not supplied as columns in the conditional_data are treated as above.

Value

A data frame suitable for the newdata argument for predict functions.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
library(tidyext)
create_prediction_data(iris)
create_prediction_data(iris, num = median,
                       expand.grid(
                         Sepal.Width=c(0,3,5),
                         Species = c('setosa', 'virginica')
                         )
                       )
create_prediction_data(iris, num = function(x) quantile(x, p=.75))

test_mod = lm(mpg  ~ wt + cyl, mtcars)
nd = create_prediction_data(test_mod$model)
predict(test_mod, newdata = nd)

m-clark/visibly documentation built on Oct. 28, 2020, 5:33 p.m.