markfairbanks / tidytable

Tidy interface to 'data.table'
https://markfairbanks.github.io/tidytable/
Other
449 stars 33 forks source link

ifelse.() cannot handle stop() #688

Closed exsell-jc closed 1 year ago

exsell-jc commented 1 year ago
# tidytable
ifelse.(aa == 1, stop('1'), stop('2'))

# dplyr
ifelse(aa == 1, stop('1'), stop('2'))
markfairbanks commented 1 year ago

FYI ifelse() is actually a base R function. dplyr's version is if_else().

base::ifelse() already handles stop() differently from dplyr::if_else(). In this case dplyr always uses the stop() even though it shouldn't.

x <- 1

base::ifelse(x == 1, 1, stop("2"))
#> [1] 1

dplyr::if_else(x == 1, 1, stop("2"))
#> Error in dplyr::if_else(x == 1, 1, stop("2")): 2

In general the use case of dplyr::if_else() is more for use on a vector instead of a single value. tidytable::ifelse.() and tidytable::if_else() (which has replaced ifelse.()) follow dplyr semantics.

x <- 1

tidytable::if_else(x == 1, 1, stop("2"))
#> Error in vec_cast_common(true = true, false = false, missing = missing, : 2

In general I would recommend using if {} else {} when testing non vector condition:

if (x == 1) {
  stop("1")
} else {
  stop("2")
}

If you have any other questions let me know.