2

gtsummary 默认情况下将组中的观察数放在该by组的标签旁边。这增加了表格的宽度......如果有很多组或 N 很大,表格会很快变得很宽。

在此处输入图像描述

是否可以让 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 以便通过手动编辑很容易显示我的意思......)

任何的想法?

谢谢!

4

2 回答 2

7

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

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()用来从标题中删除 N

此外,如果您使用flextable print engine,您可以在标题本身中添加换行符:

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()

祝你好运!

于 2020-10-14T14:16:55.547 回答
2

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

如果您想使用 {gt} 包打印表格输出到 HTML,您可以使用 HTML 标签<br>在标题行中添加换行符(非常类似于\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}")

在此处输入图像描述

于 2020-10-14T15:27:14.890 回答