如何从嵌套的小标题绘制 sjPlots?

问题描述

我使用嵌套的 tidyr 数据框创建了一些这样的模型:

set.seed(1)
library(tidyr)
library(dplyr)
library(sjplot)
library(tibble)
library(purrr)

fits <- tribble(~group,~colA,~colB,~colC,sample(c("group1","group2"),10,replace = T),sample(10,1,replace = T)) %>% 
    unnest(cols = c(colB,colC)) %>%
    nest(data=-group) %>%
    mutate(fit= map(data,~glm(formula = colA ~ colB + colC,data = .x,family="binomial"))) %>%
    dplyr::select(group,fit) %>%
    tibble::column_to_rownames("group")

我想使用这些数据来创建一些带有 sjplot::plot_models快速边际效应图

plot_models(as.list(fits),type = "pred",terms = c("colB","colA","colC"))

不幸的是,我收到错误

Error in if (fam.info$is_linear) tf <- NULL else tf <- "exp" : 
  argument is of length zero
In addition: Warning message:
Could not access model @R_113_4045@ion. 

我对数据的嵌套进行了一些尝试,但一直无法将其转换为 sjplot::plot_models 可以接受的格式。

我期望得到的是帮助文件中描述的“多元回归模型的森林图”。最终,目标是按组绘制回归模型的边际效应,我希望 plot_models 可以做到(如果我错了,请纠正我)。

解决方法

它认为原始代码和数据存在一些问题。 plot_model 不支持函数调用中的 plot_models 参数。我首先展示了一个示例,该示例展示了如何使用 {ggplot2} 的 plot_models 数据集调用 tibble 并将其与嵌套的 diamonds 一起使用。然后我将这种方法应用于 OP 的样本数据,这不会产生可用的结果*。最后,我创建了一些新的玩具数据来展示如何将该方法应用于二项式模型。

(* 在原始玩具数据中,每个模型中的因变量要么始终为 0,要么始终为 1,因此这不太可能产生可用的结果。

set.seed(1)
library(tidyr)
library(dplyr)
library(sjPlot)
library(tibble)
library(ggplot2)

# general example
fits <- tibble(id = c("x","y","z")) %>%
  rowwise() %>% 
  mutate(fit = list(glm(reformulate(
    termlabels = c("cut","color","depth","table","price",id),response = "carat"),data = diamonds)))

plot_models(fits$fit)

# OP's example data
fits2 <- tribble(~group,~colA,~colB,~colC,sample(c("group1","group2"),10,replace = T),sample(10,1,replace = T)) %>% 
  unnest(cols = c(colB,colC)) %>%
  nest(data = -group) %>%
  rowwise() %>% 
  mutate(fit = list(glm(formula = colA ~ colB + colC,data = data,family="binomial")))

plot_models(fits2$fit)
#> Warning: Transformation introduced infinite values in continuous y-axis
#> Warning: Removed 4 rows containing missing values (geom_point).

# new data for binominal model
n <- 500
g <- round(runif(n,0L,1L),0)
x1 <- runif(n,100)
x2 <- runif(n,100)
y <- (x2 - x1 + rnorm(n,sd=20)) < 0

fits3 <- tibble(g,y,x1,x2) %>% 
  nest_by(g) %>% 
  mutate(fit = list(glm(formula = y ~ x1 + x2,family="binomial")))

plot_models(fits3$fit)

reprex package (v0.3.0) 于 2021 年 1 月 23 日创建