Generate "typical" datasets for use in marginaleffects's newdata argument

typical(..., model = NULL, newdata = NULL)

Arguments

...

named arguments with vectors of values for the typical variables to construct (see Examples below.) The typical data will include combinations of unique values from these vectors

model

Model object

newdata

data.frame (one and only one of the model and newdata arguments must be true).

Value

A data.frame in which each row corresponds to one combination of the named predictors supplied by the user via the ... dots. Variables which are not explicitly defined are held at their mean or mode.

Details

If typical is used in a marginaleffects or predictions call as the newdata argument, users do not need to specify the model or newdata argument. The data is extracted automatically from the model.

If users supply a model, the data used to fit that model is retrieved using the insight::get_data function.

Examples

# The output only has 2 rows, and all the variables except `hp` are at their
# mean or mode.
typical(newdata = mtcars, hp = c(100, 110))
#>        mpg    cyl     disp     drat      wt     qsec     vs      am   gear
#> 1 20.09062 6.1875 230.7219 3.596563 3.21725 17.84875 0.4375 0.40625 3.6875
#> 2 20.09062 6.1875 230.7219 3.596563 3.21725 17.84875 0.4375 0.40625 3.6875
#>     carb  hp
#> 1 2.8125 100
#> 2 2.8125 110

# We get the same result by feeding a model instead of a data.frame
mod <- lm(mpg ~ hp, mtcars)
typical(model = mod, hp = c(100, 110))
#>    hp
#> 1 100
#> 2 110

# Use in `marginaleffects` to compute "Typical Marginal Effects"
marginaleffects(mod, newdata = typical(hp = c(100, 110)))
#>   rowid     type term        dydx  std.error  hp predicted
#> 1     1 response   hp -0.06822828 0.01011930 100  23.27603
#> 2     2 response   hp -0.06822828 0.01011878 110  22.59375