if_else running both branches?

tibble::tibble(
  foo = "bar",
  meh = NA_character
) %>%
  dplyr::group_by(foo) %>%
  dplyr::mutate(
    min_val = dplyr::if_else(
      all(is.na(meh)),
      min(meh),
      min(meh, na.rm = TRUE)
    )
  )

In the code above I expect min(meh) to run, which will become min(NA) and thus result in NA.
Instead, I'm always seeing a warning

Warning message:
Problem with `mutate()` column `min_val`.
ℹ `min_val = dplyr::if_else(all(is.na(meh)), min(meh), min(meh, na.rm = TRUE))`.
ℹ no non-missing arguments, returning NA
ℹ The warning occurred in group 1: foo = "bar". 

this warning should only occur when the else branch is run too with this data because min(meh, na.rm = TRUE) will become min(NULL) which triggers that warning.

What is going on and can I ignore the warning?
Note: using ifelse from base works fine, but drops types so it's not as useful in my real-world application.

You can ignore the warning if the results are correct.
Here is the dplyr::if_else code you can see that our has replace_with run on it for both condition and the negation of the condition, either one can therefore through warnings/errors

> dplyr::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 <- true[rep(NA_integer_, length(condition))]
    out <- replace_with(out, condition, true, fmt_args(~true), 
        glue("length of {fmt_args(~condition)}"))
    out <- replace_with(out, !condition, false, fmt_args(~false), 
        glue("length of {fmt_args(~condition)}"))
    out <- replace_with(out, is.na(condition), missing, fmt_args(~missing), 
        glue("length of {fmt_args(~condition)}"))
    out
}
<bytecode: 0x55b0005646c0>
<environment: namespace:dplyr>

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.