---
webr:
packages: [dplyr, broom, broom.helpers, cardx, car, parameters, smd, survival, gtsummary] # gtsummary last (so its functions are not masked by other packages)
resources: [R/setup.R]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# Exercises {#sec-exercises}
```{webr}
#| include: false
source("R/setup.R")
library(survival)
```
Let's build a full set of publication tables with new data.
Each problem has an **empty code cell**; write your code there and run it with "Run Code".
Sample solutions are collapsed.
## Data: survival data of lung cancer patients (`lung`)
This is data on 228 patients with advanced lung cancer, bundled with the survival package.
It is awkward to use as is, so we first tidy it in the cell below (already run).
```{webr}
lung_df <- lung |>
mutate(
sex = factor(sex, levels = 1:2, labels = c("Male", "Female")),
death = as.integer(status == 2), # 1 = death, 0 = censored
ecog = factor(ph.ecog, levels = 0:3), # performance status (ECOG PS)
age_grp = factor(ifelse(age >= 65, "65+", "<65"), levels = c("<65", "65+"))
) |>
select(time, death, age, age_grp, sex, ecog, ph.karno, wt.loss)
# add variable labels (the names shown in tables)
attr(lung_df$time, "label") <- "Follow-up (days)"
attr(lung_df$death, "label") <- "Death"
attr(lung_df$age, "label") <- "Age (years)"
attr(lung_df$age_grp, "label") <- "Age group"
attr(lung_df$sex, "label") <- "Sex"
attr(lung_df$ecog, "label") <- "ECOG performance status"
attr(lung_df$ph.karno, "label") <- "Karnofsky score"
attr(lung_df$wt.loss, "label") <- "Weight loss (lbs)"
head(lung_df)
```
::: {.callout-tip}
Variable labels can be set with `attr(x, "label") <- "..."`. Using `set_variable_labels()` from the labelled package is even easier.
:::
## Problem 1: A basic Table 1
For `lung_df`, create a patient characteristics table **by sex (`sex`)**. Requirements:
- Variables: `age`, `ecog`, `ph.karno`, `wt.loss`, `death`
- `age` as **mean (SD)**, other continuous variables as median (Q1, Q3)
- Add an overall column at the **far left**
```{webr}
#| autorun: false
```
::: {.callout-tip collapse="true"}
## Sample solution
```{webr}
lung_df |>
tbl_summary(
by = sex,
include = c(age, ecog, ph.karno, wt.loss, death),
statistic = age ~ "{mean} ({sd})"
) |>
add_overall(last = FALSE)
```
:::
## Problem 2: Add p-values
Add p-values to the table from Problem 1. Requirements:
- **t-test** for `age`, **Fisher's exact test** for `ecog`, the default tests for the rest
- Show p-values with 3 decimal places and bold those below 0.05
```{webr}
#| autorun: false
```
::: {.callout-tip collapse="true"}
## Sample solution
```{webr}
lung_df |>
tbl_summary(
by = sex,
include = c(age, ecog, ph.karno, wt.loss, death),
statistic = age ~ "{mean} ({sd})"
) |>
add_overall(last = FALSE) |>
add_p(
test = list(age ~ "t.test", ecog ~ "fisher.test"),
pvalue_fun = label_style_pvalue(digits = 3)
) |>
bold_p()
```
Fisher's test for `ecog` can take a long time to compute when there are many cells.
In that case you can use a simulated p-value with `test.args = ecog ~ list(simulate.p.value = TRUE)`.
:::
## Problem 3: Polish the appearance
Polish the table from Problem 2 as follows.
- Bold variable names
- Group headers in the form "**Male** (line break) n = 138"
- A spanning header "**Sex**" above the groups
- Title "Table 1. Baseline characteristics"
```{webr}
#| autorun: false
```
::: {.callout-tip collapse="true"}
## Sample solution
```{webr}
lung_df |>
tbl_summary(
by = sex,
include = c(age, ecog, ph.karno, wt.loss, death),
statistic = age ~ "{mean} ({sd})"
) |>
add_overall(last = FALSE) |>
add_p(
test = list(age ~ "t.test", ecog ~ "fisher.test"),
pvalue_fun = label_style_pvalue(digits = 3)
) |>
bold_p() |>
bold_labels() |>
modify_header(all_stat_cols(stat_0 = FALSE) ~ "**{level}** \nn = {n}") |>
modify_spanning_header(all_stat_cols(stat_0 = FALSE) ~ "**Sex**") |>
modify_caption("**Table 1. Baseline characteristics**")
```
`all_stat_cols(stat_0 = FALSE)` means "the group columns, excluding the overall column (`stat_0`)".
:::
## Problem 4: A stratified table
**Stratify by age group (`age_grp`)** and create a table comparing `ph.karno`, `wt.loss` and `death` by sex within each stratum (with p-values, missing rows hidden).
```{webr}
#| autorun: false
```
::: {.callout-tip collapse="true"}
## Sample solution
```{webr}
lung_df |>
select(age_grp, sex, ph.karno, wt.loss, death) |>
tbl_strata(
strata = age_grp,
.tbl_fun = ~ .x |>
tbl_summary(by = sex, missing = "no") |>
add_p(),
.header = "**Age {strata}**, N = {n}"
)
```
:::
## Problem 5: A Cox regression table (univariable + multivariable)
With time to death `Surv(time, death)` as the outcome, create a table that places side by side the hazard ratios from
- a **univariable Cox regression** for each of `age`, `sex` and `ecog`
- a **multivariable Cox regression** including all three at once
```{webr}
#| autorun: false
```
::: {.callout-tip collapse="true"}
## Sample solution
```{webr}
t_uv <- lung_df |>
tbl_uvregression(
method = coxph,
y = Surv(time, death),
exponentiate = TRUE,
include = c(age, sex, ecog),
hide_n = TRUE
)
t_mv <- coxph(Surv(time, death) ~ age + sex + ecog, data = lung_df) |>
tbl_regression(exponentiate = TRUE)
tbl_merge(
tbls = list(t_uv, t_mv),
tab_spanner = c("**Univariable**", "**Multivariable**")
) |>
bold_labels()
```
There is only one patient with ECOG = 3, so the confidence interval for that HR is extremely wide.
In a real paper, you would consider remedies such as combining levels (e.g., merging 2–3).
:::
## Problem 6: Cite numbers in the text
From the multivariable model table in Problem 5, extract **the hazard ratio for women versus men (with 95% CI and p-value)** using `inline_text()`.
```{webr}
#| autorun: false
```
::: {.callout-tip collapse="true"}
## Sample solution
```{webr}
t_mv <- coxph(Surv(time, death) ~ age + sex + ecog, data = lung_df) |>
tbl_regression(exponentiate = TRUE)
inline_text(t_mv, variable = sex, level = "Female",
pattern = "HR {estimate} (95% CI {conf.low}–{conf.high}); {p.value}")
```
:::
## Challenges
1. Set `theme_gtsummary_journal("jama")`, rebuild the table from Problem 3, and check the differences (don't forget `reset_gtsummary_theme()` at the end)
2. Add `add_difference(everything() ~ "smd")` to the table from Problem 1 to show the balance between sexes as SMDs
3. Turn the multivariable Cox regression from Problem 5 into a forest plot using the methods of @sec-forest (`plot()` is fine; ggplot2 / ggstats must be loaded)
4. On your own PC, save the table from Problem 3 to Word with `as_flex_table() |> flextable::save_as_docx(path = "table1.docx")`
Great work!