Learn R Programming

marginaleffects (version 0.1.0)

counterfactual: Generate "counterfactual" datasets for use in marginaleffects's newdata argument

Description

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

Usage

counterfactual(..., model = NULL, data = NULL)

Arguments

...

named arguments with vectors of values for the variables to construct (see Examples below.)

model

Model object

data

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

Value

A data.frame where each row of the original data is repeated multiple times for each of the values of the variables in the at list. See example below.

Details

If counterfactual is used in a marginaleffects or predictions call as the newdata argument, users do not need to specify the model or data 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.

If users supply a model, the data used to fit that model is retrieved using the insight::get_data function, and then replicated with different values of the variables in the at list.

Examples

Run this code
# NOT RUN {
# All rows are repeated twice, with different values of `hp`
cd <- counterfactual(data = mtcars, hp = c(100, 110))
cd[cd$rowid %in% 1:3,]

# We get the same result by feeding a model instead of a data.frame
mod <- lm(mpg ~ hp + wt, mtcars)
cd <- counterfactual(model = mod, hp = c(100, 110))
cd[cd$rowid %in% 1:3,]

# Use in `marginaleffects` to compute "Counterfactual Average Marginal Effects"
marginaleffects(mod, newdata = counterfactual(hp = c(100, 110)))
# }

Run the code above in your browser using DataLab