Search code examples
rcpu-wordflextablegtsummary

gtsummary: how to wrap cell output when outputting to word_document


friendly folks of SO.

Q: Is there some way when printing flextable objects to Word (via .Rmd, output = word_document), to specify that text is wrapped within cells?

Context: I use the amazing gtsummary package frequently, and the default formatting for output = html_document is perfect. On occasion, I have a cell value that is in some absurd units* and has value, eg, 1,000,000,000. When I create a tbl_summary object, there is wrapping between the Median, Q1, and Q1 for the html output and the table appears reasonable because of this wrapping within the cells. However, if I print to Word, there is no such wrapping and 1,000,000,000 (500,000,000 , 2,000,000,000) is printed on one line in the cell, maxing the table much wider than the width of the Word page. This is easily fixable in Word with, eg, Autofit Content, but: is there a way to ensure text wrapping from within R so that the table looks good without modification?

My gtsummary objects are being printed with flextable.

library(flextable)
library(gtsummary)

large_measurement <- rnorm(nrow(trial), mean = 1*10^12, sd = 1)
trial %>%
  mutate(some_measurement = large_measurement) %>%
  tbl_summary(by = trt) %>%
  add_p(pvalue_fun = ~style_pvalue(.x, digits = 2)) %>%
  add_overall() 

Thank you!

  • Relatedly -- is there a gtsummary solution for this? eg style_scinot?

Solution

  • Hmmm, the flextable pkg allows us to use "\n" to place a line break within a cell. Would it work for you to place the the median and IQR on separate rows?

    library(gtsummary)
    #> #BlackLivesMatter
    packageVersion("gtsummary")
    #> [1] '1.5.0'
    
    large_measurement <- rnorm(nrow(trial), mean = 1*10^2, sd = 1)
    tbl <-
      trial %>%
      mutate(some_measurement = large_measurement, .before = 1) %>%
      select(1:4) %>%
      tbl_summary(
        by = trt,
        missing = "no",
        # use "\n" to place a line break in statistic 
        statistic = some_measurement ~ "{median}\n({p25}, {p75})"
      ) %>%
      add_p(pvalue_fun = ~style_pvalue(.x, digits = 2)) %>%
      add_overall() %>%
      # you'll need to fix the automatic footnote to remove the line break
      modify_footnote(all_stat_cols() ~ "Median (IQR)") %>%
      as_flex_table()
    

    enter image description here Created on 2021-11-19 by the reprex package (v2.0.1)