Skip to content

Commit

Permalink
Merge branch 'main' into type-checkers
Browse files Browse the repository at this point in the history
  • Loading branch information
topepo committed Oct 31, 2024
2 parents f7dedb1 + bdb7e40 commit 4902983
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
27 changes: 26 additions & 1 deletion R/cut.R
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,38 @@ prep.step_cut <- function(x, training, info = NULL, ...) {
)
}

create_full_breaks <- function(var, breaks) {
create_full_breaks <- function(var, breaks, call = rlang::caller_env()) {
if (!is.numeric(var)) {
cli::cli_abort(
"{.arg var} must be a numeric vector, not {.obj_type_friendly {var}}.",
call = call
)
}

if (!is.numeric(breaks)) {
cli::cli_abort(
"{.arg breaks} must be a numeric vector, not {.obj_type_friendly {breaks}}.",
call = call
)
}

if (any(is.na(var))) {
cli::cli_warn(
"{.arg var} contains missing values. These will be ignored in break
calculations.",
call = call
)
var <- var[!is.na(var)]
}

if (min(var) < min(breaks)) {
breaks <- c(min(var), breaks)
}

if (max(var) > max(breaks)) {
breaks <- c(max(var), breaks)
}

sort(breaks)
}

Expand Down
23 changes: 23 additions & 0 deletions tests/testthat/test-cut.R
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,28 @@ test_that("tidy method works", {
)
})

test_that("step_cut() provides informative error on missing values", {
# Single missing value
mtcars_with_na <- mtcars
mtcars_with_na[1, "mpg"] <- NA

expect_warning(
recipe(~ ., data = mtcars_with_na) %>%
step_cut(mpg, breaks = 20) %>%
prep()
)

# Multiple missing values
mtcars_with_nas <- mtcars
mtcars_with_nas[c(1, 3, 5), "mpg"] <- NA

expect_warning(
recipe(~ ., data = mtcars_with_nas) %>%
step_cut(mpg, breaks = 20) %>%
prep()
)
})

test_that("breaks argument are type checked", {
expect_snapshot(
error = TRUE,
Expand All @@ -188,6 +210,7 @@ test_that("breaks argument are type checked", {
)
})


# Infrastructure ---------------------------------------------------------------

test_that("bake method errors when needed non-standard role columns are missing", {
Expand Down

0 comments on commit 4902983

Please sign in to comment.