---
title: "gtsummary examples"
author: "Martin LARSEN"
date: "2025-03-19"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# install.packages("gtsummary")
library(gtsummary)

# In the regression model you might be asked to install the two packages:
# 1. broom.helpers
# 2. cardx
# If so, please reply Yes to install the two packages

```

# gtsummary package

Examples taken from: https://r-graph-gallery.com/package/gtsummary.html#:~:text=The%20gtsummary%20package%20in%20R,code%20and%20publication%2Dready%20tables!

## Basic usage

```{r}
data(iris)
library(gtsummary)

iris %>%
  tbl_summary()
```


## Regression model results
```{r Regression model results}
# load dataset
data(Titanic)
df = as.data.frame(Titanic)

# load library
library(gtsummary)

# create the model
model = glm(Survived ~ Age + Class + Sex + Freq, family=binomial, data=df)

# generate table 
model %>%
  tbl_regression() %>% # regression summary function
  add_global_p() %>% # add p-values
  bold_labels() %>% # make label in bold
  italicize_levels() # make categories in label in italic
```

## Summarize table

```{r}
# load dataset and filter to keep just a few columns
data(mtcars) 
mtcars = mtcars %>%
  select(vs, mpg, drat, hp, gear)

# load package
library(gtsummary)

# create summary table
mtcars %>%
  tbl_summary(
    by=vs, # group by the `vs` variable (dichotomous: 0 or 1)
    statistic = list(
      all_continuous() ~ "{mean} ({sd})", # will display: mean (standard deviation)
      all_categorical() ~ "{n} / {N} ({p}%)" # will display: n / N (percentage)
    )
  ) %>%
  add_overall() %>% # statistics for all observations
  add_p() %>% # add p-values
  bold_labels() %>% # make label in bold
  italicize_levels() # make categories in label in italic
```

## Custom style of the table

```{r}
data(iris)
library(gtsummary)
library(gt)

iris %>%
  tbl_summary(by=Species) %>%
  add_overall() %>% # info ignoring the `by` argument
  add_n() %>% # number of observations
  modify_header(label ~ "**Variables from the dataset**") %>% # title of the variables
  modify_spanning_header(c("stat_0", "stat_1", "stat_2", "stat_3") ~ "*Descriptive statistics of the iris flowers*, grouped by Species") %>%
  as_gt() %>%
  gt::tab_source_note(gt::md("*The iris dataset is probably the **most famous** dataset in the world*"))
```


