Search code examples
rgtsummary

Having trouble using unweighted_n in header with gtsummary (version 2.0.1)


enter image description here

How to change the weighted N count in the column header ("N = 6,194") of the table above to unweighted n count?

The table was created with a default dataset using the following code:

library(gtsummary)
library(survey)
data(api)

svydesign(id = ~dnum, weights = ~pw, data = apiclus1, fpc = ~fpc) |>
tbl_svysummary(include = c(api00, stype), 
               statistic = list(all_continuous() ~ "{mean} ({sd})", 
                                all_categorical() ~ "{n_unweighted} ({p}%)")) 

Thank you for your help!


Solution

  • To get the header with unweighted statistics. You'll first need to install the development version of the package. I've included code below to install and build the table. Hope it helps!

    pak::pak("ddsjoberg/gtsummary")
    #> ℹ Loading metadata database
    #> ✔ Loading metadata database ... done
    #> 
    #> 
    #> ℹ No downloads are needed
    #> ✔ 1 pkg + 62 deps: kept 63 [1m 5.3s]
    packageVersion("gtsummary")
    #> [1] '2.0.1.9002'
    
    library(gtsummary)
    library(survey)
    data(api)
    
    svydesign(id = ~dnum, weights = ~pw, data = apiclus1, fpc = ~fpc) |>
      tbl_svysummary(
        include = c(api00, stype), 
        statistic = list(all_continuous() ~ "{mean} ({sd})", 
                         all_categorical() ~ "{n_unweighted} ({p}%)")
      ) |> 
      modify_header(all_stat_cols() ~ "**N = {n_unweighted}**") |> 
      as_kable() # convert to kable to display on stackoverflow
    
    Characteristic N = 183
    api00 644 (106)
    stype
    E 144 (79%)
    H 14 (7.7%)
    M 25 (14%)

    Created on 2024-08-25 with reprex v2.1.1

    Note: In your example, for the stype variable we're mixing unweighted counts (n_unweighted) and weighted proportions (p).