Search code examples
rgtsummary

How to set "na.rm = TRUE " within R glue syntax


I am using gtsummary::tbl_summary to create a stats summary table.

stats_summary_table <-
  dat_wide%>%
  tbl_summary(by = mss_plate_id, 
              missing = "no",
              statistic = list(all_continuous() ~ " {mean} ± {sd}   {cv}"  ))

The cv function is from goeveg library. The report table shows cv value as 0. I suppose it is because of missing value in my data. So, my question is how to write cv(x, na.rm = TRUE) in the glue syntax.

Edit: It turns out that the challenge is due to the precision issue but not setting na.rm=TRUE. So the solution is to set digits to 2 or 3 for cv. (see the marked answer and the comments with it)


Solution

  • This is a great question.

    One of the difficult things tbl_summary() tries to do is guess how many digits to round statistics to. This example is tricky because you'll often want the mean and the CV to be shown at different levels of precision since they are not on the same scale. In the example below, tbl_summary() guessed that age should be shown rounded to the nearest integer. This is a reasonable assumption for the mean and SD, but we need to tell it to show more digits for CV. To do this, we use the tbl_summary(digits=) argument. There are three statistics being shown for age (mean, sd, and cv), and we'll pass a vector of length three, indicating how many digits to round each statistic to.

    library(goeveg)
    library(gtsummary)
    
    trial %>%
      select(age, marker) %>%
      tbl_summary(
        statistic = list(all_continuous() ~ " {mean} ± {sd} [{cv}]"),
        digits = list(age ~ c(0, 0, 2))
      )
    

    enter image description here

    Hope this answers your question! Happy Coding!