Irene
Irene

Reputation: 43

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

I am using a .R script for analyses, and printing to a word document using rmarkdown::render. For formatted output I am using the gtsummary library, and as I want to loop through multiple variables I have the models within a for loop. The models run, however the output is not being printed to the word document - even with the results = 'asis' option included.

Script 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)
}

Script 2

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

Upvotes: 4

Views: 556

Answers (1)

akrun
akrun

Reputation: 886958

We could change the print to 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))
}

In the render call

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

-output

enter image description here

Upvotes: 1

Related Questions