-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtlf-baseline.qmd
More file actions
238 lines (183 loc) · 7.11 KB
/
Copy pathtlf-baseline.qmd
File metadata and controls
238 lines (183 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
---
title: "Baseline characteristics"
---
::: callout-tip
## Objective
Create baseline characteristics tables to summarize demographic and clinical characteristics of study participants at enrollment.
Learn to calculate descriptive statistics by treatment group using Polars and format regulatory-compliant tables with rtflite.
:::
## Overview
Baseline characteristics tables summarize the demographic and clinical characteristics of study participants at enrollment. Following [ICH E3 guidance](https://database.ich.org/sites/default/files/E3_Guideline.pdf), these tables are essential for understanding the study population and assessing comparability between treatment groups.
This tutorial shows you how to create a baseline characteristics table using Python's `rtflite` package.
<embed src="pdf/tlf_baseline.pdf" style="width:100%; height:600px" type="application/pdf">
```{python}
import polars as pl # Data manipulation
import rtflite as rtf # RTF reporting
```
```{python}
#| echo: false
# Configure Polars to show only first 5 rows
pl.Config.set_tbl_rows(5)
```
## Step 1: Load data
We start by loading the Subject-level Analysis Dataset (ADSL) and filtering to the safety population.
```{python}
adsl = (
pl.read_parquet("data/adsl.parquet")
.select(["USUBJID", "TRT01P", "AGE", "SEX", "RACE"])
)
adsl
```
## Step 2: Calculate summary statistics
We'll create separate functions to handle continuous and categorical variables.
### Continuous variables (age)
For continuous variables, we calculate mean (SD) and median [min, max].
```{python}
def summarize_continuous(df, var):
"""Calculate summary statistics for continuous variables"""
return df.group_by("TRT01P").agg([
pl.col(var).mean().round(1).alias("mean"),
pl.col(var).std().round(2).alias("sd"),
pl.col(var).median().alias("median"),
pl.col(var).min().alias("min"),
pl.col(var).max().alias("max"),
pl.len().alias("n")
])
age_stats = summarize_continuous(adsl, "AGE")
age_stats
```
### Categorical variables (sex, race)
For categorical variables, we calculate counts and percentages.
```{python}
def summarize_categorical(df, var):
"""Calculate counts and percentages for categorical variables"""
# Get counts by treatment and category
counts = df.group_by(["TRT01P", var]).len()
# Get treatment totals for percentage calculations
totals = df.group_by("TRT01P").len().rename({"len": "total"})
# Calculate percentages
result = counts.join(totals, on="TRT01P").with_columns([
(100.0 * pl.col("len") / pl.col("total")).round(1).alias("pct")
])
return result
sex_stats = summarize_categorical(adsl, "SEX")
sex_stats
```
```{python}
race_stats = summarize_categorical(adsl, "RACE")
race_stats
```
## Step 3: Format results
Now we format the statistics into the standard baseline table format.
### Format age statistics
```{python}
# Format age as "Mean (SD)" and "Median [Min, Max]"
age_formatted = age_stats.with_columns([
pl.format("{} ({})", pl.col("mean"), pl.col("sd")).alias("mean_sd"),
pl.format("{} [{}, {}]", pl.col("median"), pl.col("min"), pl.col("max")).alias("median_range")
]).select(["TRT01P", "mean_sd", "median_range"])
age_formatted
```
### Format categorical statistics
```{python}
# Format categorical as "n (%)"
sex_formatted = sex_stats.with_columns(
pl.format("{} ({}%)", pl.col("len"), pl.col("pct")).alias("n_pct")
).select(["TRT01P", "SEX", "n_pct"])
race_formatted = race_stats.with_columns(
pl.format("{} ({}%)", pl.col("len"), pl.col("pct")).alias("n_pct")
).select(["TRT01P", "RACE", "n_pct"])
sex_formatted
```
## Step 4: Create table structure
We'll build the table row by row following the standard baseline table format.
```{python}
# Helper function to get value for a treatment group
def get_value(df, treatment):
"""Get value for a specific treatment group or return default"""
result = df.filter(pl.col("TRT01P") == treatment)
return result[result.columns[-1]][0] if result.height > 0 else "0 (0.0%)"
# Build the baseline table structure
table_rows = []
# Age section
table_rows.append(["Age (years)", "", "", ""])
# Age Mean (SD) row
age_mean_row = [" Mean (SD)"] + [
get_value(age_formatted.select(["TRT01P", "mean_sd"]), trt).replace("0 (0.0%)", "")
for trt in ["Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"]
]
table_rows.append(age_mean_row)
# Age Median [Min, Max] row
age_median_row = [" Median [Min, Max]"] + [
get_value(age_formatted.select(["TRT01P", "median_range"]), trt).replace("0 (0.0%)", "")
for trt in ["Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"]
]
table_rows.append(age_median_row)
# Sex section
table_rows.append(["Sex", "", "", ""])
for sex_cat in ["Female", "Male"]:
sex_data = sex_formatted.filter(pl.col("SEX") == sex_cat)
sex_row = [f" {sex_cat}"] + [
get_value(sex_data, trt)
for trt in ["Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"]
]
table_rows.append(sex_row)
# Race section
table_rows.append(["Race", "", "", ""])
for race_cat in ["White", "Black Or African American", "American Indian Or Alaska Native"]:
race_data = race_formatted.filter(pl.col("RACE") == race_cat)
race_row = [f" {race_cat}"] + [
get_value(race_data, trt)
for trt in ["Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"]
]
table_rows.append(race_row)
# Create DataFrame from table rows
baseline_table = pl.DataFrame(
table_rows,
schema=["Characteristic", "Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"],
orient="row"
)
baseline_table
```
## Step 5: Generate publication-ready output
Finally, we format the baseline table for regulatory submission using the `rtflite` package.
```{python}
# Get treatment group sizes for column headers
treatment_n = adsl.group_by("TRT01P").len().sort("TRT01P")
n_placebo = treatment_n.filter(pl.col("TRT01P") == "Placebo")["len"][0]
n_low = treatment_n.filter(pl.col("TRT01P") == "Xanomeline Low Dose")["len"][0]
n_high = treatment_n.filter(pl.col("TRT01P") == "Xanomeline High Dose")["len"][0]
doc_baseline = rtf.RTFDocument(
df=baseline_table,
rtf_title=rtf.RTFTitle(
text=[
"Baseline Characteristics of Participants",
"(All Participants Randomized)"
]
),
rtf_column_header=rtf.RTFColumnHeader(
text=[
"Characteristic",
f"Placebo\n(N={n_placebo})",
f"Xanomeline Low Dose\n(N={n_low})",
f"Xanomeline High Dose\n(N={n_high})"
],
text_justification=["l", "c", "c", "c"],
col_rel_width=[3, 2, 2, 2]
),
rtf_body=rtf.RTFBody(
text_justification=["l", "c", "c", "c"],
col_rel_width=[3, 2, 2, 2]
),
rtf_source=rtf.RTFSource(text=["Source: ADSL dataset"])
)
doc_baseline.write_rtf("rtf/tlf_baseline.rtf") # Save as RTF for submission
```
```{python}
#| echo: false
# Convert RTF to PDF
from rtflite import LibreOfficeConverter
converter = LibreOfficeConverter()
converter.convert("rtf/tlf_baseline.rtf", output_dir="pdf/", format="pdf", overwrite=True)
```
<embed src="pdf/tlf_baseline.pdf" style="width:100%; height:600px" type="application/pdf">