## Creating Marginal Effect Plots for Linear Regression Models in R

Suppose we estimate the model $E(y) = \beta_0 + \beta_xx + \beta_zz + \beta_{xz}xz$ and want to calculate the the marginal effect of $x$ on $E(y)$ as $z$ varies $\left(\dfrac{\partial E(y)}{\partial x}\right)$ and its 90% confidence interval. Brambor, Clark, and Golder describe exactly how to do this and provide Stata code. Below is a bit of R code to do something similar.

## Simulate an Interactive Process

The first step is to simulate an interactive data set.

We can plot the data to get a sense of the pattern using compactr .

## Estimate a Model with a Product Term

The next step is to estimate a model with a product term and pull out the estimated coefficients (needed to calculate the marginal effects) and the variance-covariance matrix (needed to calculate the standard errors). This is easily done using the R code below.

And a quick look at the estimates shows that our product term is statistically significant (p < 0.05), indicating that we can reject the (null) hypothesis of constant effects.

## Estimating the Marginal Effects and Confidence Intervals

The first step is to choose a set of values for z over which to compute the marginal effect of x. This is necessary because the marginal effect of x depends on z.

In particular, $\dfrac{\partial E(y)}{\partial x} = \beta_x + \beta_{xz}z$. We can use the fact to get the point estimates of the marginal effect of x.

Getting the standard errors is a little tedious, but we can use the nice table on Matt's page to avoid having to work it out ourselves. Referring to that table, we see that the variance of the marginal effect is given by $\sigma^2_{me} = Var(\beta_x) + z^2Var(\beta_{xz}) + 2zCov(\beta_x\beta_{xz})$. The standard error is simply the square root of this quantity, which we can easily compute in R.

To get the 90% confidence interval for each estimated marginal effect (one for each z in the R object  z0 ), we simply go up and down 1.64 standard errors from the estimate.

## Creating the Marginal Effect Plot

All that is left is to plot the estimates and confidence intervals. I prefer to do this in my R package  compactr , but you can use whatever you like.

Here's the entire bit of code in one frame for your convenience.