从 R 脚本循环 tbl_regression 未打印 rmarkdown::render

looped tbl_regression from R script not printing for rmarkdown::render

我正在使用 .R 脚本进行分析,并使用 rmarkdown::render 打印到 word 文档。对于格式化输出,我使用 gtsummary 库,因为我想遍历多个变量,所以我在 for 循环中有模型。模型 运行,但输出未打印到 word 文档 - 即使包含结果 = 'asis' 选项。

脚本 1

library(gtsummary)  # formatted model output

#'# Example dataset
dataset = as.data.frame(cbind(Y1 = c(rep(0,10), rep(1,10)),
                        Y2 = c(rep(0,5), rep(1,10), rep(0,5)),
                        X = rnorm(20, 0, 1)))
  
#'# Loop with formatted output
#+ Table1, results = 'asis'
for(i in c("Y1", "Y2")){
  fit = glm( paste("get(i) ~", "X") ,
             family = binomial,
             data = dataset)
  
  print(length(fit$residuals))
  
  fit2 = fit %>%  
    tbl_regression(
      exponentiate = TRUE, 
      conf.level = 0.999,
      pvalue_fun = ~style_pvalue(.x, digits = 3),
    ) %>% 
    bold_p(t = 0.01) %>%
    bold_labels() %>%
    italicize_levels() 

  fit2
  
  print(fit2)
}

脚本 2

#'# Print to word document
rmarkdown::render('C:\Users ... Test.R',
                  output_format = "word_document",
                  output_dir = "C:\Users ...")

我们可以将 print 更改为 knit_print

for(i in c("Y1", "Y2")){
  fit = glm( paste("get(i) ~", "X") ,
             family = binomial,
             data = dataset)
  
  print(length(fit$residuals))
  
  fit2 = fit %>%  
    tbl_regression(
      exponentiate = TRUE, 
      conf.level = 0.999,
      pvalue_fun = ~style_pvalue(.x, digits = 3),
    ) %>% 
    bold_p(t = 0.01) %>%
    bold_labels() %>%
    italicize_levels() 
  
  fit2
  
  cat(knitr::knit_print(fit2))
}

render调用

knitr::opts_chunk$set(
                      echo=FALSE, warning=FALSE, message=FALSE)
rmarkdown::render(input_file,
                  output_format = "word_document",
                  output_dir = output_dir,  quiet = TRUE)

-输出