diff --git a/R/if-else2.R b/R/if-else2.R index 37bf0a8..da39494 100644 --- a/R/if-else2.R +++ b/R/if-else2.R @@ -35,5 +35,8 @@ #' x3 = dplyr::if_else(str_detect2(y, "x is false"), FALSE, x) #' ) if_else2 <- function(condition, true, false) { + if (!any(condition)) { + stop("No matches found. Did not make any replacements.") + } dplyr::if_else(condition, true, false, missing = false) } diff --git a/tests/testthat/test-if-else2.R b/tests/testthat/test-if-else2.R index 8e58d45..bb995f4 100644 --- a/tests/testthat/test-if-else2.R +++ b/tests/testthat/test-if-else2.R @@ -27,3 +27,11 @@ test_that("works with lists", { list(1, 2, NULL) ) }) + +test_that("throws an informative error when no matches are found", { + x <- c(1, 2, 3, 4, 5) + expect_error( + if_else2(x < 0, 0, x), + "No matches found. Did not make any replacements." + ) +})