From 69e74305386094cb1fc0b10495d18492cec5b012 Mon Sep 17 00:00:00 2001 From: Andrei <92amartins@gmail.com> Date: Fri, 22 Sep 2023 11:20:51 -0300 Subject: [PATCH] Improve labeller() behavior for lookup tables (#5432) --- NEWS.md | 3 +++ R/labeller.R | 6 +++++- tests/testthat/test-labellers.R | 12 ++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 65572857c7..1d95e88137 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # ggplot2 (development version) +* `labeller()` now handles unspecified entries from lookup tables + (@92amartins, #4599). + * `fortify.default()` now accepts a data-frame-like object granted the object exhibits healthy `dim()`, `colnames()`, and `as.data.frame()` behaviors (@hpages, #5390). diff --git a/R/labeller.R b/R/labeller.R index c367a2aa11..8d2a3884be 100644 --- a/R/labeller.R +++ b/R/labeller.R @@ -450,7 +450,11 @@ labeller <- function(..., .rows = NULL, .cols = NULL, # Apply named labeller one by one out <- lapply(names(labels), function(label) { if (label %in% names(labellers)) { - labellers[[label]](labels[label])[[1]] + # Yield custom labels with any NA replaced with original + lbls <- labellers[[label]](labels[label])[[1]] + ind <- which(is.na(lbls)) + lbls[ind] <- .default(labels[label])[[1]][ind] + lbls } else { .default(labels[label])[[1]] } diff --git a/tests/testthat/test-labellers.R b/tests/testthat/test-labellers.R index 0e352e3b26..460349e960 100644 --- a/tests/testthat/test-labellers.R +++ b/tests/testthat/test-labellers.R @@ -20,3 +20,15 @@ test_that("labeller function catches overlap in names", { ) expect_snapshot_error(ggplotGrob(p)) }) + +test_that("labeller handles badly specified labels from lookup tables", { + df <- data_frame0(am = c(0, 1)) + labs <- labeller(am = c("0" = "Automatic", "11" = "Manual")) + expect_equal(labs(df), list(am = c("Automatic", "1"))) +}) + +test_that("labeller allows cherry-pick some labels", { + df <- data_frame0(am = c(0, 1)) + labs <- labeller(am = c("0" = "Automatic")) + expect_equal(labs(df), list(am = c("Automatic", "1"))) +})