I don't think if_else is feasible or preferable over base ifelse in this case. dplyr::if_else uses subsetting in its source (use if_else without brackets). To recreate the error, try running min[].
We can try to "repair" the function by altering the code that intends to coerce the output to be of the same class as the true and false values by subsetting it:
out <- true[rep(NA_integer_, length(condition))]
# to pseudocode
out <- "whatever the typeof(true) value is"
and use ::: to get the appropriate internal functions that dplyr uses.
if_else <- function (condition, true, false, missing = NULL) {
if (!is.logical(condition)) {
bad_args("condition", "must be a logical vector, not {friendly_type_of(condition)}.")
}
out <- NA_integer_
out <- dplyr:::replace_with(out, condition, true, dplyr:::fmt_args(~true),
glue::glue("length of {fmt_args(~condition)}"))
out <- dplyr:::replace_with(out, !condition, false, dplyr:::fmt_args(~false),
glue::glue("length of {fmt_args(~condition)}"))
out <- dplyr:::replace_with(out, is.na(condition), missing, dplyr:::fmt_args(~missing),
glue::glue("length of {fmt_args(~condition)}"))
out
}
x = 5
if_else(x == 2, min, max)
Error: `true` must be an integer vector, not a primitive function.
This error is the result of a type check in internal function check_type within replace_with, that looks like this:
if (identical(typeof(x), typeof(template))) {return()}
Here template is out, defined in if_else.
- typeof Na_Integer_ is "integer"
- typeof min is "builtin"
A solution to outputting a function min or max from dplyr::if_else would then be how to coerce out to be of type "builtin", and to redefinedplyr internal functions, for example replace_with that uses another another subsetting operation that fails for the same reason as min[].
That is, changing out to a builtin like min still throws an error:
if_else <- function(...){
...
out <- # if out <- min
...
}
Error in x[i] <- val : object of type 'builtin' is not subsettable
So, this is intended behavior, but perhaps object of type 'builtin' is not subsettable is not the intended error message to be displayed.