counterfactual: Generate "counterfactual" datasets for use in...

Description Usage Arguments Details Value Examples

View source: R/counterfactual_typical.R

Description

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

Usage

1
counterfactual(..., model = NULL, newdata = NULL)

Arguments

...

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

model

Model object

newdata

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

Details

If counterfactual 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.

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.

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.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# All rows are repeated twice, with different values of `hp`
cd <- counterfactual(newdata = 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)))

marginaleffects documentation built on Oct. 19, 2021, 1:09 a.m.