#==============================================================================
# Create the dataset
#==============================================================================
library(tidyverse)
adsl01 <- tribble(
~usubjid, ~sex, ~age, ~trt01pn,
"101", "M", 25, 1,
"102", "F", 30, 2,
"103", "M", 27, 1
)
#==============================================================================
# Assign labels and lengths using attr()
#==============================================================================
attr(adsl01$usubjid, "label") <- "Unique Subject Identifier"
attr(adsl01$usubjid, "length") <- 10
attr(adsl01$sex, "label") <- "Sex"
attr(adsl01$sex, "length") <- 1
attr(adsl01$age, "label") <- "Age"
attr(adsl01$age, "length") <- 8
attr(adsl01$trt01pn, "label") <- "Planned Treatment for Period 01 (N)"
attr(adsl01$trt01pn, "length") <- 8
#==============================================================================
# View all labels and lengths
#==============================================================================
# Create a tibble with variable names and their labels
label_table <- tibble(
variable = names(adsl01),
label = map_chr(adsl01, ~ attr(.x, "label")),
length = map_int(adsl01, ~ attr(.x, "length"))
)
- We use tribble() to define the dataset adsl01 with four variables.
- Using attr(..., "label") , we assign descriptive labels to each variable.
- Using attr(..., "length") , we assign length attribute to each variable.
- R doesn't enforce character length truncation — the "length" attribute is just metadata.
- Length attribute is just to show for documentation, or SAS-like simulation.