繁体   English   中英

如何为混合模型制作森林图

[英]How to make a forest plot for a mixed model

如何为混合模型系数及其相应的置信区间制作森林图。 我试过这段代码

Model = lme (fixed = score~ Age+Sex+yearsofeducation+walkspeed,
random = ~1|ID, 
data=DB,
na.action = na.omit, method = "ML", 
)
plot_summs (model)

但是,我希望森林地块中的 OR 以降序排列。 谢谢您的帮助。

我将其称为“系数图”,而不是“森林图”。 (当您比较来自许多不同研究的相同效应的估计值时,会在荟萃分析中使用森林图。)

示例设置

这是一个有点愚蠢的例子,但应该与你的足够接近(我不清楚你为什么提到 OR(= 优势比?),这些通常来自逻辑回归......?)

library(nlme)
mtcars <- transform(mtcars, cylgear = interaction(cyl, gear))
m1 <- lme(mpg ~ disp + hp + drat + wt + qsec,
    random = ~1|cylgear,
    data = mtcars)

系数图:dotwhisker

您可以直接从dotwhisker包中获得您想要的大致内容,但它不会对效果进行排序(或者据我所知不容易):

library(dotwhisker)
library(broom.mixed)  ## required to 'tidy' (process) lme fits
dwplot(m1, effects = "fixed")

系数图:tidyverse

我通常自己进行处理,因为我更喜欢增加灵活性。

library(tidyverse)
tt <- (m1
    ## extract estimates and CIs
    |> tidy(effects = "fixed", conf.int = TRUE)
    ## usually *don't* want to compare intercept (dwplot does this automatically)
    |> filter(term != "(Intercept)")
    ## scale parameters by 2SD - usually necessary for comparison
    |> dotwhisker::by_2sd(data = mtcars)
    ## take only the bits we need, rename some (cosmetic)
    |> select(term, estimate, lwr = conf.low, upr = conf.high)
    ## order terms by estimate value
    |> mutate(across(term, ~reorder(factor(.), estimate)))
)

gg0 <- (ggplot(tt,
               aes(estimate, term))
    + geom_pointrange(aes(xmin = lwr, xmax = upr))
    + geom_vline(xintercept = 0, lty = 2)
)
print(gg0)

在此处输入图像描述

这里唯一剩下/可能的棘手问题是,如果您有相似幅度的正系数和负系数,该怎么办。 如果要按绝对值排序,那么

|> mutate(across(term, ~reorder(factor(.), estimate, 
 FUN = function(x) mean(abs(x)))

虽然这有点难看。

如果你喜欢 tidyverse,你可以用forcats::fct_reorder代替reorder

我只是在 Ben Bolker 的出色答案中添加了一个选项:使用modelsummary包。 (免责声明:我是作者。)

使用该包,您可以使用modelplot()函数创建森林图,并使用coef_map参数重命名和重新排序系数。 如果您正在估计一个 logit 模型并想要优势比,您可以使用exponentiate参数。

您在coef_map向量中插入系数的顺序在图中从下到上对它们进行排序。 例如:

library(lme4)
library(modelsummary)

mod <- lmer(mpg ~ wt + drat + (1 | gear), data = mtcars)

modelplot(
    mod,
    coef_map = c("(Intercept)" = "Constant",
                 "drat" = "Rear Axle Ratio",
                 "wt" = "Weight"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM