# \donttest{
# Create a dictionary
my_dict <- tibble::tribble(
~Variable, ~Description,
"age", "Age at Enrollment (years)",
"marker", "Marker Level (ng/mL)",
"trt", "Treatment Group",
"grade", "Tumor Grade"
)
# Apply labels to data
trial_labeled <- gtsummary::trial |>
apply_labels_from_dictionary(my_dict)
# Now labels work automatically in gtsummary
trial_labeled |>
gtsummary::tbl_summary(by = trt, include = c(age, marker, grade))
# And in ggplot2 4.0+ (automatic axis labels!)
if (requireNamespace("ggplot2", quietly = TRUE) &&
utils::packageVersion("ggplot2") >= "4.0.0") {
library(ggplot2)
trial_labeled |>
ggplot(aes(x = age, y = marker, color = factor(trt))) +
geom_point() # Axes and legend automatically labeled!
}
# Check that labels were applied
attr(trial_labeled$age, "label") # "Age at Enrollment (years)"
# Preserve existing labels
trial_partial <- gtsummary::trial
attr(trial_partial$age, "label") <- "Existing Age Label"
trial_partial |>
apply_labels_from_dictionary(my_dict, overwrite = FALSE)
attr(trial_partial$age, "label") # Still "Existing Age Label"
attr(trial_partial$marker, "label") # "Marker Level (ng/mL)" (was added)
# }
Run the code above in your browser using DataLab