Home > Blockchain >  Want to put digits(decimals) to ONLY the separate percentage column values in tbl_summary. Any break
Want to put digits(decimals) to ONLY the separate percentage column values in tbl_summary. Any break

Time:12-08

I would want to add decimals for the percentage column only

#Separate columns library(gtsummary) library(tidyverse)

tbl <- 
  c("{n}", "{p}%") %>%         # iterate over these two statistics
  # build tbl_summary using each of the stats
  map(
    ~trial %>% 
      select(response, grade) %>% 
      tbl_summary(
        statistic = all_categorical() ~ .x,
        missing = "ifany",
    digits = list(
      all_categorical() ~ 1,
      all_continuous() ~ 0
    ),
    missing_text = "(Missing)"
      ) 
  ) %>%
  # merge the two tables together
   tbl_merge() %>%
  # some formatting to make it cute
  modify_spanning_header(everything() ~ NA) %>%
  modify_footnote(everything() ~ NA) %>%
  modify_header(list(stat_0_1 ~ "**n / N**", stat_0_2 ~ "**percent**"))

CodePudding user response:

You can conditionally add a digits= value depending on whether we're summarizing the percentage or the counts. Example below!

library(gtsummary)

tbl <- 
  c("{n}", "{p}%") %>%         # iterate over these two statistics
  # build tbl_summary using each of the stats
  purrr::map(
    ~trial %>% 
      select(response, grade) %>% 
      tbl_summary(
        statistic = all_categorical() ~ .x,
        missing = "ifany",
        digits = list(
          all_categorical() ~ ifelse(.x == "{p}%", 1, 0),
          all_continuous() ~ 0
        ),
        missing_text = "(Missing)"
      ) 
  ) %>%
  # merge the two tables together
  tbl_merge() %>%
  # some formatting to make it cute
  modify_spanning_header(everything() ~ NA) %>%
  modify_footnote(everything() ~ NA) %>%
  modify_header(list(stat_0_1 ~ "**n / N**", stat_0_2 ~ "**percent**"))

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

  • Related