legacy_marginal_effect: Analytical Average Marginal Effects

View source: R/mfx_function.R

legacy_marginal_effectR Documentation

Analytical Average Marginal Effects

Description

This function is consider "legacy" and may be removed in future updates. It calculates the (average) marginal effect and standard error by taking the analytical derivative of the conditional expectation function and only works in limited scenarios.

Usage

legacy_marginal_effect(model, data = NULL, variables = NULL)

Arguments

model

A model estimated using functions from mgcv (e.g., gam or bam).

data

A data frame that is used to calculate the marginal effect or set to NULL which will employ the data used when estimating the model. The default is NULL.

variables

A character vector that specifies the variables for which to calculate effects. The default, NULL, calculates effects for all variables.

Details

This function is designed to provide comparability with the original KRLS package, but is rather limited in the scenarios where it can be applied (e.g., limited families, limited specifications of linear predictions, limited numbers of smooth/penalized terms, etc.)

Because of these restrictions, users should rely on calculate_effects as this function may be removed in future updates. A numerical approximation to the derivative found analytically in this function is provided in calculate_effects.

Value

The function returns a list that contains the following elements:

  • "ME_pointwise": The marginal effects for each observation.

  • "ME_pointwise_var": The variance for each pointwise marginal effect in "ME_pointwise".

  • "AME_pointwise": The average marginal effect, i.e. the column averages of "ME_pointwise".

  • "AME_pointwise_var": The variance of each average marginal effect.

Examples

set.seed(321)
n <- 100
x1 <- rnorm(n)
x2 <- rnorm(n)
x3 <- rnorm(n)
state <- sample(letters, n, replace = TRUE)
y <- 0.3 * x1 + 0.4 * x2 + 0.5 * x3 + rnorm(n)
data <- data.frame(y, x1, x2, x3, state)

# A gKRLS model
fit_gKRLS <- mgcv::gam(y ~ s(x1, x2, x3, bs = "gKRLS"), data = data)
# calculate marginal effect using derivative
legacy_marginal_effect(fit_gKRLS)


gKRLS documentation built on Sept. 11, 2024, 8:24 p.m.