Marginal effect of beta at different values with corresponding confidence intervals

133 Views Asked by At

Basically I have a mixed-effect model with 2 predictors, an interaction term and a random effect that looks like this:

x1<-abs(rnorm(300)) #continuous variable
x2<-sample(c(1,2,3), 300, replace = T) #discrete variable 
x3<-sample(c("A","B","C"), 300, replace = T) #categorical variable 
y<-abs(rnorm(300)) #continuous variable
df<-as.data.frame(cbind(as.numeric(x1),as.numeric(x2),x3,as.numeric(y)))

m1=lmer(y~x1*x2+(1|x3),data=df)
summary(m1)

I used lme4 to create such a model. I want to find the marginal effect of x1 on y (the beta coefficient) at different levels of x2 (which is a factor with 3 levels).

I would also like to get the confidence interval of beta at each level and plot such results.

1

There are 1 best solutions below

0
On

You may want to try the marginaleffects package. (Disclaimer: I am the maintainer.)

library(lme4)
library(marginaleffects)

x1<-abs(rnorm(300)) #continuous variable
x2<-sample(c(1,2,3), 300, replace = T) #discrete variable 
x3<-sample(c("A","B","C"), 300, replace = T) #categorical variable 
y<-abs(rnorm(300)) #continuous variable
df<-as.data.frame(cbind(as.numeric(x1),as.numeric(x2),x3,as.numeric(y)))
m1 <- lmer(y~x1*x2+(1|x3),data=df)

marginaleffects(m1, variables = "x1", newdata = typical(x2 = 1:3, x3 = "B"))
##   rowid     type term        dydx  std.error        x1 x2 x3 predicted
## 1     1 response   x1 -0.04269402 0.08814210 0.7792904  1  B 0.9280228
## 2     2 response   x1  0.03476429 0.05850354 0.7792904  2  B 0.8708736
## 3     3 response   x1  0.11222260 0.09286114 0.7792904  3  B 0.8137245