Skip to content

Improve labeller() behavior for lookup tables #5432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
6 changes: 5 additions & 1 deletion R/labeller.R
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
}
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-labellers.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")))
})