30-Day Course
Clinical SAS → R
Day 16 of 30·Clinical Data Handling & CDISC Basics

Clinical Data in R: Labels, Formats & Controlled Terminology

Carrying metadata through an R workflow with labelled and haven.

Learning objectives

  • 1Apply and read variable labels in R.
  • 2Work with SAS formats as labelled vectors.
  • 3Manage controlled terminology as factors / lookups.
  • 4Keep metadata intact from import to export.

Key SAS® → R comparison

TaskSAS®R
Variable labellabel age='Age';var_label(df$age) <- 'Age'
Value formatproc format; valuelabelled values / factor labels
Controlled termformat + CT datasetfactor(levels=CT) / join to CT

Code examples

Labelling a derived variable
SAS®
data adsl; set adsl;
  label trt01pn='Planned Treatment (N)';
run;
R
library(labelled)
adsl <- adsl |>
  mutate(trt01pn = as.integer(trt01p == "Drug")) |>
  set_variable_labels(trt01pn = "Planned Treatment (N)")

Note: Labels live as attributes and are written back into .xpt/.sas7bdat on export.

Explanation

Clinical datasets are defined as much by their metadata as their values. The labelled package, working with haven, lets you set and read variable labels and value labels so that the define-able attributes a reviewer expects travel through every transformation.

Controlled terminology can be enforced either by encoding variables as factors with the permitted levels, or by joining against a CT reference table — the latter scaling better when terminology versions change.

Practice exercise

Import an ADSL, set labels on two derived variables, encode a categorical as a factor using a controlled-terminology level set, and confirm the labels persist after a write_xpt()/read_xpt() round-trip.