Skip to content
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

Fix col_labels bug for named label attributes #301

Merged
merged 10 commits into from
Mar 1, 2024
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# teal.data 0.5.0.9001

### Bug fixes
* Fixed bug in `col_labels` causing incorrect label names to be returned when input data contains named label attributes.

# teal.data 0.5.0

### Bug fixes
Expand Down
3 changes: 2 additions & 1 deletion R/formatters_var_labels.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ col_labels <- function(x, fill = FALSE) {
return(character(0L))
}

labels <- lapply(x, attr, "label")
labels <- sapply(x, function(i) as.vector(attr(i, "label")), simplify = FALSE, USE.NAMES = TRUE)
lapply(labels, checkmate::assert_string, .var.name = "attr(x, \"label\")", null.ok = TRUE)
pawelru marked this conversation as resolved.
Show resolved Hide resolved

nulls <- vapply(labels, is.null, logical(1L))
if (any(nulls)) {
Expand Down
31 changes: 31 additions & 0 deletions tests/testthat/test-formatters_var_labels.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,37 @@ testthat::test_that("col_labels returns a vector of column names when fill = TRU
)
})

testthat::test_that("col_labels works with labels having additional attributes (including names)", {
x <- iris
attr(x$Species, "label") <- structure("Label for Species", names = "blah", foo = "bar")
testthat::expect_identical(col_labels(x)[["Species"]], "Label for Species")
})

testthat::test_that("col_labels returns only 'names' attribute and ignores all the rest", {
x <- iris
attr(x$Species, "label") <- structure("Label for Species", names = "blah", foo = "bar")
testthat::expect_identical(attributes(col_labels(x)["Species"]), list(names = "Species"))
})

testthat::test_that("col_labels throws if label is not a character", {
x <- iris
attr(x$Species, "label") <- structure(1, names = "blah", foo = "bar")
testthat::expect_error(
col_labels(x),
"Assertion on 'attr(x, \"label\")' failed",
fixed = TRUE
)
})

testthat::test_that("col_labels throws if label is not a character of length 1", {
x <- iris
attr(x$Species, "label") <- structure(c("a", "b"), names = "blah", foo = "bar")
testthat::expect_error(
col_labels(x),
"Assertion on 'attr(x, \"label\")' failed",
fixed = TRUE
)
})

# col_labels ----
testthat::test_that("col_labels<- value accepts character vector", {
Expand Down
Loading