首页 > 解决方案 > 将多个双变量多级模型结果组合到一个显示表中

问题描述

我在 R markdown 中进行分析,我想查看血红蛋白(结果)和可能影响它的其他几个变量(暴露,例如季节和 ses)之间的关系。

我想首先创建几个以血红蛋白为结果的模型,并分别查看每个暴露变量。

我有多级数据 - 我每人有不止一次观察,所以我使用 glmmTMB 包进行多级建模。

这是我的一些数据的示例:

data = data.frame(id = c(1,1,1,2,2,2,3,3,3), 
                 ses = c(0.13, 1.23, -0.78, 1.32, 0.56, -0.04, -1.43, 1.45, 2.01),
                 season = c("good", "good", "bad", "bad", "bad", "good", "good", "good", "good" ),
                 haemoglobin = c(15, 14, 16, 9, 10, 11, 12, 10, 11))

# id   ses season haemoglobin
# 1  1  0.13   good          15
# 2  1  1.23   good          14
# 3  1 -0.78    bad          16
# 4  2  1.32    bad           9
# 5  2  0.56    bad          10
# 6  2 -0.04   good          11
# 7  3 -1.43   good          12
# 8  3  1.45   good          10
# 9  3  2.01   good          11

这是我将使用的两个模型的示例:

library(glmmTMB)
mod1 <- glmmTMB(haemoglobin ~ season + (1 | id), data = data)
summary(mod1)
confint(mod1)
mod2 <- glmmTMB(haemoglobin ~ ses + (1 | id), data = data)
summary(mod2)
confint(mod2)

我的问题是如何在表格中呈现我的数据而无需手动输入所有数据(即,以防我的估计发生变化,所以我不必再次输入!)也许我可以使用 kable 但我不确定如何。

我想要一个看起来像这样的表(如下)。它不必完全相同,只是允许我同时显示几个双变量模型的结果。

table = data.frame(Variable = c("seasonbad","seasongood","ses"), 
                  Estimate = c("ref", 0.05188, -0.650),
                  Confint = c("-", "-1.62, 1.72", "-1.01, 0.29"),
                  Pval = c("-", 0.951, 0.000442))
# Variable Estimate     Confint     Pval
# 1  seasonbad      ref           -        -
# 2 seasongood  0.05188 -1.62, 1.72    0.951
# 3        ses    -0.65 -1.01, 0.29 0.000442

任何帮助/软件包建议将不胜感激。非常感谢!

标签: rhtml-tabler-markdownkableglmmtmb

解决方案


这更像是一个数据操作问题,而不是关于 html/markdown 的问题。你需要从 mod 对象中获取你想要的数据,一旦你有了剩下的就很容易了。这是我的意思的一个例子:

# define a function to extract the info and returns it in the shape you need
get_summary <- function(mod){
  mod_summary <- summary(mod)
  mod_conf <- confint(mod)
  
  var <- dimnames(mod_summary$coefficients$cond)[[1]][-1]
  res_mod <- mod_conf[paste0("cond.", var), 1:3] %>% t() %>% data.frame()
  res_mod["Pval"] <- mod_summary$coefficients$cond[var, 4]
  res_mod["Variable"] <- var
  return(res_mod)
}

# get the data from each model and bind the rows of the results together
rbind(get_summary(mod1), get_summary(mod2)) %>%
  # show the result as an HTML table
  tableHTML(rownames = FALSE, round = 2,widths = rep(100, 5)) %>% 
  add_theme("rshiny-blue")

你应该得到这样的东西:

在此处输入图像描述


推荐阅读