Tables with gt and gtsummary

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(gtsummary)
mpg |> 
  select(cyl, cty, hwy) |> 
  tbl_summary()
Characteristic N = 2341
cyl
    4 81 (35%)
    5 4 (1.7%)
    6 79 (34%)
    8 70 (30%)
cty 17 (14, 19)
hwy 24 (18, 27)
1 n (%); Median (Q1, Q3)
mpg |> 
  tbl_cross(row = fl, col = cyl, percent = "cell")
cyl
Total
4 5 6 8
fl




    c 1 (0.4%) 0 (0%) 0 (0%) 0 (0%) 1 (0.4%)
    d 3 (1.3%) 0 (0%) 1 (0.4%) 1 (0.4%) 5 (2.1%)
    e 0 (0%) 0 (0%) 1 (0.4%) 7 (3.0%) 8 (3.4%)
    p 22 (9.4%) 0 (0%) 17 (7.3%) 13 (5.6%) 52 (22%)
    r 55 (24%) 4 (1.7%) 60 (26%) 49 (21%) 168 (72%)
Total 81 (35%) 4 (1.7%) 79 (34%) 70 (30%) 234 (100%)
trial |> 
  head()
# A tibble: 6 × 8
  trt      age marker stage grade response death ttdeath
  <chr>  <dbl>  <dbl> <fct> <fct>    <int> <int>   <dbl>
1 Drug A    23  0.16  T1    II           0     0    24  
2 Drug B     9  1.11  T2    I            1     0    24  
3 Drug A    31  0.277 T1    II           0     0    24  
4 Drug A    NA  2.07  T3    III          1     1    17.6
5 Drug A    51  2.77  T4    III          1     1    16.4
6 Drug B    39  0.613 T4    I            0     1    15.6
library(gapminder)
gapminder |> 
  select(continent, year, lifeExp) |>
  filter(year  %in% c(1952, 2007)) |>
  tbl_cross(row = continent, col = year, percent = "row")
year
Total
1952 2007
continent


    Africa 52 (50%) 52 (50%) 104 (100%)
    Americas 25 (50%) 25 (50%) 50 (100%)
    Asia 33 (50%) 33 (50%) 66 (100%)
    Europe 30 (50%) 30 (50%) 60 (100%)
    Oceania 2 (50%) 2 (50%) 4 (100%)
Total 142 (50%) 142 (50%) 284 (100%)
回到顶部