---
webr:
packages: [dplyr, broom, broom.helpers, cardx, car, parameters, smd, gtsummary] # gtsummary は最後(他パッケージに関数を上書きされないように)
resources: [R/setup.R]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# 層別・表の結合 {#sec-strata}
```{webr}
#| include: false
source("R/setup.R")
```
## 層別した表:`tbl_strata()`
「グレードごとに、治療群を比較した表を横に並べたい」という場合に使います。
```{webr}
trial |>
select(grade, trt, age, response) |>
tbl_strata(
strata = grade,
.tbl_fun = ~ .x |>
tbl_summary(by = trt, missing = "no") |>
add_p()
)
```
- `strata`:層に分ける変数
- `.tbl_fun`:各層のデータ `.x` に対して作る表。`~ .x |> ...` の形で書く
- 層ごとの表が横に結合され、上に層の名前(スパナー)が付く
::: {.callout-note}
## 赤字の警告が出たら
`cannot compute exact confidence intervals with ties` という警告は、Wilcoxon 検定で「同じ値(タイ)があるので正確な信頼区間が計算できない」という意味です。
表に出る p 値には影響しないので、ここでは気にしなくて大丈夫です。
:::
### 層の見出しを変える:`.header`
```{webr}
trial |>
select(grade, trt, age, response) |>
tbl_strata(
strata = grade,
.tbl_fun = ~ .x |> tbl_summary(by = trt, missing = "no"),
.header = "**Grade {strata}**, N = {n}"
)
```
`{strata}` に層の値、`{n}` に層の人数が入ります。`**` で囲むと太字になります。
### 縦に積む:`.combine_with`
```{webr}
trial |>
select(grade, trt, age, response) |>
tbl_strata(
strata = grade,
.tbl_fun = ~ .x |> tbl_summary(by = trt, missing = "no") |> add_p(),
.combine_with = "tbl_stack" # 既定は "tbl_merge"(横並び)
)
```
## 表を横に並べる:`tbl_merge()`
別々に作った表を横に結合します。たとえば「腫瘍縮小」と「死亡」それぞれについての集計を並べる例:
```{webr}
t_resp <- trial |>
tbl_summary(by = response, include = c(age, grade), missing = "no",
label = list(age ~ "Age", grade ~ "Grade")) |>
add_p()
t_death <- trial |>
tbl_summary(by = death, include = c(age, grade), missing = "no",
label = list(age ~ "Age", grade ~ "Grade")) |>
add_p()
tbl_merge(
tbls = list(t_resp, t_death),
tab_spanner = c("**Tumor Response**", "**Death**")
)
```
::: {.callout-note}
`tbl_merge()` は **変数名とラベルで行を突き合わせ** ます。結合する表の変数・ラベルはそろえておきましょう。
:::
## 表を縦に積む:`tbl_stack()`
```{webr}
t_a <- trial |> filter(trt == "Drug A") |>
tbl_summary(include = c(age, response), missing = "no")
t_b <- trial |> filter(trt == "Drug B") |>
tbl_summary(include = c(age, response), missing = "no")
tbl_stack(
tbls = list(t_a, t_b),
group_header = c("Drug A", "Drug B")
)
```
## クロス集計表:`tbl_cross()`
2つのカテゴリ変数の分割表を作ります。
```{webr}
trial |>
tbl_cross(row = stage, col = trt, percent = "row", margin = "row") |>
add_p()
```
## 連続変数の群別要約:`tbl_continuous()`
「グレード × 治療群ごとの年齢の中央値」のように、**1つの連続変数** を2つのカテゴリで要約します。
```{webr}
trial |>
tbl_continuous(
variable = age,
by = trt,
include = c(grade, stage)
)
```
::: {.callout-important}
## この章のまとめ
- `tbl_strata()`:層ごとに同じ表を作って横(または縦)に並べる
- `tbl_merge()`:別々の表を横に結合。`tab_spanner` で上見出し
- `tbl_stack()`:別々の表を縦に積む。`group_header` で区切り見出し
- `tbl_cross()`(分割表)、`tbl_continuous()`(連続変数をカテゴリ×群で要約)
:::