Day 18 of 30·Clinical Data Handling & CDISC Basics
Reshaping: pivot_longer() & pivot_wider() vs. PROC TRANSPOSE
Move between wide and long layouts — the backbone of BDS datasets.
Learning objectives
- 1Reshape long-to-wide and wide-to-long with tidyr.
- 2Replace PROC TRANSPOSE patterns.
- 3Understand why BDS/ADaM favors the long layout.
- 4Handle multiple measure columns in one pivot.
Key SAS® → R comparison
| Task | SAS® | R |
|---|---|---|
| Wide to long | proc transpose | pivot_longer() |
| Long to wide | proc transpose (id/var) | pivot_wider() |
| Many measures | multiple transposes | pivot_longer(cols, names_to) |
Code examples
SAS®
proc transpose data=vs out=long;
by usubjid visit;
var sysbp diabp pulse;
run;R
library(tidyr)
long <- vs |>
pivot_longer(
cols = c(sysbp, diabp, pulse),
names_to = "PARAMCD",
values_to = "AVAL"
)Note: One pivot_longer() turns several measure columns into PARAMCD/AVAL rows — the shape ADaM BDS expects.
Explanation
Reshaping is central to clinical programming because the BDS structure underlying most ADaM datasets is fundamentally long: one row per subject-parameter-timepoint. tidyr's pivot_longer() and pivot_wider() express these transforms more transparently than chained PROC TRANSPOSE steps.
pivot_longer() can collapse many measure columns into a parameter/value pair in a single call, while pivot_wider() rebuilds a wide layout for, say, a listing — all without intermediate transposed datasets to track.
Practice exercise
Transpose a wide vitals dataset (SYSBP, DIABP, PULSE per visit) into PARAMCD/AVAL long format, then pivot a subset back to wide for a by-visit listing.