Skip to content

Commit 4e7a78c

Browse files
committed
Improve labeller() behavior for lookup tables
1 parent de7bad6 commit 4e7a78c

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# ggplot2 (development version)
22

3+
* `labeller()` now handles unspecified entries from lookup tables
4+
(@92amartins, #4599).
5+
36
* `fortify.default()` now accepts a data-frame-like object granted the object
47
exhibits healthy `dim()`, `colnames()`, and `as.data.frame()` behaviors
58
(@hpages, #5390).

R/labeller.R

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,11 @@ labeller <- function(..., .rows = NULL, .cols = NULL,
450450
# Apply named labeller one by one
451451
out <- lapply(names(labels), function(label) {
452452
if (label %in% names(labellers)) {
453-
labellers[[label]](labels[label])[[1]]
453+
# Yield custom labels with any NA replaced with original
454+
lbls <- labellers[[label]](labels[label])[[1]]
455+
ind <- which(is.na(lbls))
456+
lbls[ind] <- .default(labels[label])[[1]][ind]
457+
lbls
454458
} else {
455459
.default(labels[label])[[1]]
456460
}

tests/testthat/test-labellers.R

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,15 @@ test_that("labeller function catches overlap in names", {
2020
)
2121
expect_snapshot_error(ggplotGrob(p))
2222
})
23+
24+
test_that("labeller handles badly specified labels from lookup tables", {
25+
df <- data_frame0(am = c(0, 1))
26+
labs <- labeller(am = c("0" = "Automatic", "11" = "Manual"))
27+
expect_equal(labs(df), list(am = c("Automatic", "1")))
28+
})
29+
30+
test_that("labeller allows cherry-pick some labels", {
31+
df <- data_frame0(am = c(0, 1))
32+
labs <- labeller(am = c("0" = "Automatic"))
33+
expect_equal(labs(df), list(am = c("Automatic", "1")))
34+
})

0 commit comments

Comments
 (0)