Skip to content

Commit

Permalink
Better error for col_factor with non-character levels
Browse files Browse the repository at this point in the history
Fixes #1140
  • Loading branch information
jimhester committed Mar 3, 2021
1 parent 780ed64 commit 9fd1160
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# readr (development version)

* `col_factor()` now throws a more informative error message if given non-character levels (#1140)

* `write_csv()` now errors if given a matrix column (#1171)

* `write_csv()` now again is able to write data with duplicated column names (#1169)
Expand Down
3 changes: 3 additions & 0 deletions R/collectors.R
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,9 @@ parse_factor <- function(x, levels = NULL, ordered = FALSE, na = c("", "NA"),
#' @rdname parse_factor
#' @export
col_factor <- function(levels = NULL, ordered = FALSE, include_na = FALSE) {
if (!(is.null(levels) || is.character(levels))) {
stop(sprintf("`levels` must be `NULL` or a character vector:\n- `levels` is a '%s'", class(levels)), call. = FALSE)
}
collector("factor", levels = levels, ordered = ordered, include_na = include_na)
}

Expand Down
4 changes: 4 additions & 0 deletions tests/testthat/test-parsing-factors.R
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,7 @@ test_that("Can parse a factor with levels of NA and empty string", {
as.integer(factor(x, levels = c("NA", "NB", "NC", "")))
)
})

test_that("factor levels must be null or a character vector (#1140)", {
expect_error(col_factor(levels = 1:10), "must be `NULL` or a character vector")
})

0 comments on commit 9fd1160

Please sign in to comment.