边际效应

statistics
Published

2024-11-10

Modified

today

边际均值和边际效应

Show the code
library(ggeffects)
m <- lm(Petal.Width ~ Petal.Length + Species, data = iris)

marginaleffects::avg_slopes(m, variables = "Species")

                        Contrast Estimate Std. Error    z Pr(>|z|)    S 2.5 %
 mean(versicolor) - mean(setosa)    0.435      0.103 4.23   <0.001 15.4 0.234
 mean(virginica) - mean(setosa)     0.838      0.145 5.76   <0.001 26.9 0.553
 97.5 %
  0.637
  1.123

Term: Species
Type:  response 
Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted 
Show the code
out <- predict_response(m, "Species", margin = "empirical")
out
# Average predicted values of Petal.Width

Species    | Predicted |     95% CI
-----------------------------------
setosa     |      0.77 | 0.61, 0.94
versicolor |      1.21 | 1.15, 1.27
virginica  |      1.61 | 1.48, 1.74

边际效应

ggeffects 描述单个自变量的作用,Petal.Length 对Petal.Width 的边际效应

Show the code
library(ggeffects)
pred <- ggpredict(m, terms = "Petal.Length")
ggplot(pred, aes(x, predicted)) +
  geom_line() +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.1) +
  theme_classic() +
  labs(x = "Petal.Length", y = "Petal.Width")