我目前正在處理 30 個具有相同列名但數字資料不同的資料集。我需要將線性混合模型和廣義線性模型應用于資料集的每個實體,并在森林圖上繪制生成的固定效應系數。
資料目前的結構如下(為簡單起見,對每個串列元素使用相同的資料集):
library(lme4)
data_list <- list()
# There's definitely a better way of doing this through lapply(), I just can't figure out how
for (i in 1:30){
data_list[[i]] <- tibble::as_tibble(mtcars) # this would originally load different data at every instance
}
compute_model_lmm <- function(data){
lmer("mpg ~ hp disp drat (1|cyl)", data = data)
}
result_list_lmm <- lapply(data_list, compute_model_lmm)
我目前正在做的是
library(modelsummary)
modelplot(result_list_lmm)
facet_wrap(~model) #modelplot() takes arguments/functions from ggplot2

這需要大量的時間,但它有效。
現在,我想在同一個圖上比較另一個模型,如
compute_model_glm <- function(data){
glm("mpg ~ hp disp drat cyl", data = data)
}
result_list_glm <- lapply(data_list, compute_model_glm)
modelplot(list(result_list_lmm[[1]], result_list_glm[[1]]))

但對于情節的每個實體。
我如何指定它modelplot()?
提前致謝!
uj5u.com熱心網友回復:
該modelplot函式為您提供了一些繪制系數和區間的基本方法(facet例如,檢查引數)。
然而,函式的真正威力來自于使用draw=FALSE引數。在這種情況下,modelplot很難在方便的資料框中為您提供估計值,包括所有重命名、穩健的標準錯誤和modelplot函式的其他實用程式。然后,您可以使用該資料框自己進行繪圖以ggplot2進行無限自定義。
library(modelsummary)
library(ggplot2)
results_lm <- lapply(1:10, function(x) lm(hp ~ mpg, data = mtcars)) |>
modelplot(draw = FALSE) |>
transform("Function" = "lm()")
results_glm <- lapply(1:10, function(x) glm(hp ~ mpg, data = mtcars)) |>
modelplot(draw = FALSE) |>
transform("Function" = "glm()")
results <- rbind(results_lm, results_glm)
head(results)
term model estimate std.error conf.low conf.high Function
1 (Intercept) Model 1 324.0823 27.4333 268.056 380.1086 lm()
3 (Intercept) Model 2 324.0823 27.4333 268.056 380.1086 lm()
5 (Intercept) Model 3 324.0823 27.4333 268.056 380.1086 lm()
7 (Intercept) Model 4 324.0823 27.4333 268.056 380.1086 lm()
9 (Intercept) Model 5 324.0823 27.4333 268.056 380.1086 lm()
11 (Intercept) Model 6 324.0823 27.4333 268.056 380.1086 lm()
ggplot(results, aes(y = term, x = estimate, xmin = conf.low, xmax = conf.high))
geom_pointrange(aes(color = Function), position = position_dodge(width = .5))
facet_wrap(~model)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358906.html
