Skip to content

Commit

Permalink
- added error = FALSE argument to if_else2()
Browse files Browse the repository at this point in the history
---
added more `if_else2()` tests
resolves #26
  • Loading branch information
dunkenwg committed Nov 20, 2024
1 parent 277cede commit fb8f21d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
5 changes: 3 additions & 2 deletions R/if-else2.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#' [`str_detect2()`].
#'
#' @inherit dplyr::if_else
#' @param error A logical value. If `TRUE`, provides an informative error message if no matches are found.
#' @return Where condition is `TRUE`, the matching value from `true`, where it's `FALSE` or `NA`, the matching value from `false`.
#' @seealso [`ifelse()`] and [`dplyr::if_else()`].
#' @export
Expand Down Expand Up @@ -34,8 +35,8 @@
#' dplyr::mutate(data,
#' x3 = dplyr::if_else(str_detect2(y, "x is false"), FALSE, x)
#' )
if_else2 <- function(condition, true, false) {
if (!any(condition)) {
if_else2 <- function(condition, true, false, error = FALSE) {
if (!any(condition) & error == TRUE) {
stop("No matches found. Did not make any replacements.")
}
dplyr::if_else(condition, true, false, missing = false)
Expand Down
4 changes: 3 additions & 1 deletion man/if_else2.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 18 additions & 2 deletions tests/testthat/test-if-else2.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,26 @@ test_that("works with lists", {
)
})

test_that("throws an informative error when no matches are found", {
test_that("throws an informative error when error = TRUE and no matches are found", {
x <- c(1, 2, 3, 4, 5)
expect_error(
if_else2(x < 0, 0, x),
if_else2(x < 0, 0, x, error = TRUE),
"No matches found. Did not make any replacements."
)
})

test_that("doesn't throws an informative error when error = TRUE and matches are found", {
x <- c(-1, 2, 3, 4, 5)
expect_equal(
if_else2(x < 0, 0, x, error = TRUE),
c(0, 2, 3, 4, 5)
)
})

test_that("doesn't throw an informative error when error = FALSE (the default) and no matches are found", {
x <- c(1, 2, 3, 4, 5)
expect_equal(
if_else2(x < 0, 0, x),
x
)
})

0 comments on commit fb8f21d

Please sign in to comment.