如何绘制交互作用项标准差变化的边际效应?

How to plot a marginal effect of a standard deviation change of an interaction term?

提问人:Victor Shin 提问时间:9/29/2023 更新时间:9/29/2023 访问量:78

问:

我想绘制交互作用项的标准差变化的边际效应。 我正在尝试绘制交互作用项的条件边际效应,即模型的偏导数(斜率),但由于我的数据的性质和变化,单位变化可能有点误导。因此,我想将数字转换为标准差变化而不是单位变化,这样我就可以获得实质性效果,以便更好地解释。我目前正在使用边际效应包来绘制它。所以,这里有一个例子。

假设我有以下模型,我想看看 hp 对 disp 值的 mpg 的边际影响(例如,我不确定这些变量是什么意思):

data(mtcars)
mod <- lm(mpg ~ hp * disp + factor(am), data = mtcars)
summary(mod)

Call:
lm(formula = mpg ~ hp * disp + factor(am), data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.3599 -1.7385 -0.2522  0.7915  5.2211 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  3.600e+01  3.678e+00   9.786 2.25e-10 ***
hp          -9.196e-02  2.441e-02  -3.767 0.000816 ***
disp        -5.418e-02  1.858e-02  -2.915 0.007062 ** 
factor(am)1  2.289e+00  1.455e+00   1.573 0.127297    
hp:disp      2.269e-04  9.377e-05   2.419 0.022563 *  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.623 on 27 degrees of freedom
Multiple R-squared:  0.835, Adjusted R-squared:  0.8105 
F-statistic: 34.15 on 4 and 27 DF,  p-value: 3.355e-10

为了查看条件边际效应,我使用边际效应包绘制了该图:

library(marginaleffects)
plot1 <- plot_slopes(mod, variables = "hp", condition = "disp") +
      geom_hline(yintercept=0,linetype=2) +
      geom_rug(aes(x=disp), data=mtcars, sides="b") +
      theme_grey()
    plot1

结果如下图所示:

Marginal effect of hp across disp

它显示了 hp 在 disp 上的单位变化的边际效应(斜率)。我想得到的不是单位变化,而是 hp 标准差变化的边际效应。我愿意使用其他软件包和替代方法来绘制边际效应。不确定边际效应包的可塑性如何。如果您需要进一步澄清,请告诉我。

ggplot2 R-边际效应

评论


答:

1赞 Allan Cameron 9/29/2023 #1

显而易见的解是感兴趣的变量(在本例中),它等价于 。这样,1 个单位的更改将是 1 个标准差的更改。scalehp(hp - mean(hp))/sd(hp)

library(marginaleffects)
library(ggplot2)

mtcars2 <- within(mtcars, hp <- scale(hp)[,1])
mod <- lm(mpg ~ hp * disp + factor(am), data = mtcars2)

plot_slopes(mod, variables = "hp", condition = "disp") +
  geom_hline(yintercept = 0, linetype = 2) +
  geom_rug(aes(x = disp), data = mtcars2, sides = "b") +
  theme_grey()

创建于 2023-09-28 with reprex v2.0.2

3赞 Vincent 9/29/2023 #2

您可以使用该函数轻松获得此值,其中可以使用参数在预测变量中指定 1SD 的增加:plot_comparisons()variables

library(marginaleffects)

mod <- lm(mpg ~ hp * disp + factor(am), data = mtcars)

plot_comparisons(mod, variables = list(hp = "sd"), condition = "disp")

当然,在这个简单的线性模型中,@allan-Cameron 的解是等价的。这种方法的好处是,它允许进行一系列其他比较(例如:四分位数、2SD、自定义增量),而无需弄清楚正确的标准化是什么,也不必重新调整模型。

评论

0赞 Victor Shin 11/12/2023
嗨,@Vincent!有没有办法获得负 SD?
0赞 Vincent 11/12/2023
有人在 github 上提出了一个相关问题,并在这里提出了一个解决方案,其论点是:github.com/vincentarelbundock/marginaleffects/issues/......comparison
0赞 Victor Shin 11/13/2023
好的,非常感谢!