Search code examples
rpdfr-markdowngtsummary

gtsummary: Fit wide table in Markdown PDF output


I am attempting to create a patients characteristics table (table 1), which works, but since my "by" variable has 10 categories, it spills out of the PDF page.

I have tried to truncate the category names, as well as change page layout to landscape, but 1 category is still off the page.

Could you kindly show me how I can fix this?

Is there a way I can print the N and N(%) that by default appears on the column headers to appear just below the column name instead of being on the same row, so as to cut down on the width? e.g. what in your examples are:

Drug A, N = 98 (49%)1 Drug B, N = 102 (51%)1

To be:

Drug A _ _ _ _ _ _ _ _ _Drug B

N = 98 (49%)1 _ _ _ _ _ N = 102 (51%)1

Thanks


Solution

  • First, let's address the question of the column widths. We are currently preparing a new version of gtsummary to be released to CRAN next week. In the new version, there is a function called as_kable_extra() that will convert a gtsummary object to kable and add additional formatting using kableExtra. You can use this function to convert your gtummary object to use with kableExtra, then reduce the font size to make the table fit. Install the dev version of gtsummary from GitHub with remotes::install_github("ddsjoberg/gtsummary")

    Here's a code example:

    library(gtsummary)
    
    # build a tbl_summary object
    trial %>%
      select(trt, age, grade, response) %>%
      tbl_summary(by = trt, missing = "no") %>%
      # style the output with custom header
      modify_header(stat_by = "{level}") %>%
      # convert to kableExtra
      as_kable_extra(booktabs = TRUE) %>%
      # reduce font size to make table fit. 
      # you may also use the `latex_options = "scale_down"` argument here.
      kableExtra::kable_styling(font_size = 7)
    

    Similar results may be obtained using the as_flextable() function, then utilizing formatting functions available from the flextable package.

    Regarding the line breaks in the header...at the moment this is not possible. BUT, it looks quite simple to implement in the as_kable_extra() function (http://haozhu233.github.io/kableExtra/best_practice_for_newline_in_latex_table.pdf). If I get a moment, I'll add this functionality before next week's release.

    Happy Coding!