使用 gtsummary,是否可以将 N 放在列名称的单独行上?

With gtsummary, is it possible to have N on a separate row to the column name?

默认情况下,

gtsummary 将 by 组中的观察数放在该组标签的旁边。这会增加 table 的宽度...对于许多组或大 N,table 会很快变得非常宽。

是否可以让 gtsummary 在标签下方的单独一行中报告 N?例如

> data(mtcars)
> mtcars %>%
+         select(mpg, cyl, vs, am) %>%
+         tbl_summary(by = am) %>%
+         as_tibble()
# A tibble: 6 x 3
  `**Characteristic**` `**0**, N = 19`   `**1**, N = 13`  
  <chr>                <chr>             <chr>            
1 mpg                  17.3 (14.9, 19.2) 22.8 (21.0, 30.4)
2 cyl                  NA                NA               
3 4                    3 (16%)           8 (62%)          
4 6                    4 (21%)           3 (23%)          
5 8                    12 (63%)          2 (15%)          
6 vs                   7 (37%)           7 (54%)          

会变成

# A tibble: 6 x 3
  `**Characteristic**` `**0**`           `**1**`  
  <chr>                <chr>             <chr>            
1                      N = 19            N = 13
2 mpg                  17.3 (14.9, 19.2) 22.8 (21.0, 30.4)
3 cyl                  NA                NA               
4 4                    3 (16%)           8 (62%)          
5 6                    4 (21%)           3 (23%)          
6 8                    12 (63%)          2 (15%)          
7 vs                   7 (37%)           7 (54%)    

(我只用了as_tibble,这样可以很容易地通过手动编辑来表达我的意思...)

有什么想法吗?

谢谢!

这是您可以执行此操作的一种方法:

library(tidyverse)
library(gtsummary)

mtcars %>%
  select(mpg, cyl, vs, am) %>%
# create a new variable to display N in table
  mutate(total = 1) %>%
# this is just to reorder variables for table 
  select(total, everything()) %>%
  tbl_summary(
    by = am,
# this is to specify you only want N (and no percentage) for new total variable
    statistic = total ~ "N = {N}") %>%
# this is a gtsummary function that allows you to edit the header
  modify_header(stat_by = "**{level}**")
  • 首先,我正在创建一个新变量,它只是总观察值(称为 total
  • 然后,我正在自定义我希望显示该变量统计信息的方式
  • 然后我使用 gtsummary::modify_header() 从 header
  • 中删除 N

此外,如果您使用 flextable print engine,您可以在 header 本身添加一个换行符:

mtcars %>%
  select(mpg, cyl, vs, am) %>%
# create a new variable to display N in table
  tbl_summary(
    by = am
# this is to specify you only want N (and no percentage) for new total variable
    ) %>%
# this is a gtsummary function that allows you to edit the header
  modify_header(stat_by =  "{level}\nN = {N}") %>%
  as_flex_table()

祝你好运!

@kittykatstat 已经发布了两个很棒的解决方案!我将添加一个细微的变化:)

如果您想使用 {gt} 包打印 table 您正在输出到 HTML,您可以使用 HTML 标记 <br> 在 header 行中添加一个换行符(非常类似于已经发布的 \n 解决方案)。

library(gtsummary)

mtcars %>%
  select(mpg, cyl, vs, am) %>%
  dplyr::mutate(am = factor(am, labels = c("Manual", "Automatic"))) %>%
  # create a new variable to display N in table
  tbl_summary(by = am) %>%
  # this is a gtsummary function that allows you to edit the header
  modify_header(stat_by =  "**{level}**<br>N = {N}")