Learn R Programming

margins (version 0.2.0)

marginal_effects: Differentiate a Model Object

Description

Extract marginal effects (via numerical differentiation) and predicted differences in factor changes from a model object, conditional on data

Usage

marginal_effects(model, data, type = c("response", "link"),
  method = c("simple", "Richardson", "complex"))

Arguments

model

A model object, perhaps returned by lm or glm

data

A data.frame over which to calculate marginal effects.

type

A character string indicating the type of marginal effects to estimate. Mostly relevant for non-linear models, where the reasonable options are “response” (the default) or “link” (i.e., on the scale of the linear predictor in a GLM).

method

A character string indicating the numeric derivative method to use when estimating marginal effects. “simple” optimizes for speed; “Richardson” optimizes for accuracy. See grad for details.

Value

An data.frame with dimensions equal to data, where each row is an observation and each column is the marginal effect of that variable for the data values provided by data.

Details

This function uses numeric differentiation (grad) to extract marginal effects from an estimated model with respect to all numeric variables specified in data and returns a data.frame containing the unit-specific marginal effects with respect to each variable included (or not included) in the model. (Note that this is not each coefficient.) For factor variables (or character variables, which are implicitly coerced to factors by modelling functions), discrete differences in predicted outcomes are reported instead (i.e., change in predicted outcome when factor is set to a given level minus the predicted outcome when the factor is set to its baseline level). If you want to use numerical differentiation for factor variables (which you probably do not want to do), enter them into the original modelling function as numeric values rather than factors.

Variable class coercion (other than factor(x)) inside a formula passed to, for example, lm may cause weird behavior, or errors.

See Also

margins, build_margins, extract_marginal_effects

Examples

Run this code
# NOT RUN {
require("datasets")
x <- lm(mpg ~ cyl * hp + wt, data = mtcars)
marginal_effects(x)

# factor variables report discrete differences
x <- lm(mpg ~ factor(cyl) * factor(am), data = mtcars)
marginal_effects(x)

# }

Run the code above in your browser using DataLab