Home > Software design >  R formula for average partial effect of linear regression with interaction terms
R formula for average partial effect of linear regression with interaction terms

Time:12-11

What is the most efficient way to obtain the average partial effect for a variable in a multiple linear regression model that has interaction terms?

I can do this by manually finding the mean of each interaction variable and subtracting that value in a new regression, but there must be a better way.

This is the model.

install.packages('wooldridge')
data(catholic,package='wooldridge')
model<-lm(math12~cathhs cathhs*lfaminc cathhs*motheduc cathhs*fatheduc,data=data)

Is there a way to get the average partial effect for the variable "cathhs" without manually subtracting the mean from each interaction term in a new regression model?

CodePudding user response:

You can try the marginaleffects package (Disclaimer: I am the author.) This package allows you to compute many different quantities of interest, including what the documentation calls “Average Marginal Effects” (or average slopes), which sounds like what you may be looking for (the terminology in this area is super inconsistent):

library(marginaleffects)
library(wooldridge)
data(catholic, package='wooldridge')
model<-lm(math12~cathhs cathhs*lfaminc cathhs*motheduc cathhs*fatheduc,data=catholic)

mfx <- marginaleffects(model)
summary(mfx)

          Term Effect Std. Error z value   Pr(>|z|)  2.5 % 97.5 %
    1   cathhs 1.7850    0.46538   3.836 0.00012524 0.8729 2.6972
    2  lfaminc 1.8461    0.14268  12.939 < 2.22e-16 1.5665 2.1257
    3 motheduc 0.7125    0.06216  11.463 < 2.22e-16 0.5906 0.8343
    4 fatheduc 0.8928    0.05618  15.891 < 2.22e-16 0.7827 1.0029

    Model type:  lm 
    Prediction type:  response 

CodePudding user response:

One way to obtain the average partial effect is to use the margins package, which can be installed from CRAN using the following command:

install.packages("margins")

Once the margins package is installed, you can use the predict function to obtain the average partial effect for a variable in your model. Here is an example:

# Fit a multiple linear regression model with interaction terms
fit <- lm(y ~ x1   x2   x3   x1:x2   x1:x3, data = mydata)

# Obtain the average partial effect for the variable x1
library(margins)
predict(fit, newdata = data.frame(x1 = mean(mydata$x1)), type = "ap")

Another way to obtain the average partial effect for a variable in a multiple linear regression model with interaction terms is to use the aov function to fit an analysis of variance (ANOVA) model, and then use the contrast function to obtain the average partial effect for the variable of interest. Here is an example:

# Fit an ANOVA model with interaction terms
fit <- aov(y ~ x1 * x2 * x3, data = mydata)

# Obtain the average partial effect for the variable x1
contrast(fit, "x1", "ap")
  •  Tags:  
  • r
  • Related