Skip to content

Commit

Permalink
Merge pull request #25 from poissonconsulting/ifelse2
Browse files Browse the repository at this point in the history
Added informative error message to `if_else2()` if no matches are found
  • Loading branch information
aylapear authored Oct 31, 2024
2 parents 6c07e00 + 6a933df commit 4973e9e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions R/if-else2.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
8 changes: 8 additions & 0 deletions tests/testthat/test-if-else2.R
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
})

0 comments on commit 4973e9e

Please sign in to comment.