if_else() is too strict when comparing true/false values

Having trouble understanding how to accomplish this workflow, and how/why the requirements for if_else() have changed (might be inaccurate on this?)

I'm trying to use if_else() to assign how many unique values are present in a columns of a tibble. I want to use this in a group_by capacity, but have simplified the reprex below. Using a length(unique(.)) conditional, I'm attempting to either leave the column as-is, or replace with a single value (character string). An error is thrown under where I have multiple non-unique values, which I'd expect to simply use the false value, however it attempts to compare the possible true value and obviously finds that it is longer than 1???

# reprex for mutating a column using if_else()
# Expected functionality: 
#   Where a column has all identical values that value is retained,
#   where multiple values are found replace all with "Mixed" string

tibble(a=c("one","two")) %>% 
  mutate(b = if_else( length(unique(a))==1, a, "Mixed"))

Error: Problem with mutate() column b.
ℹ b = if_else(length(unique(a)) == 1, a, "Mixed").
x true must be length 1 (length of condition), not 2.
Run rlang::last_error() to see where the error occurred.

Editing to add my solution to this instance, but still interested in hearing why this functionality is helpful

> tibble(a=c("one","two")) %>% 
+   mutate(b = if_else( length(unique(a))==1,  a[1], "Mixed"))

# A tibble: 2 x 2
  a     b    
  <chr> <chr>
1 one   Mixed
2 two   Mixed

Just use ifelse() instead.

Thanks, to be honest I'd always assumed the base::ifelse() didn't handle vector conditions since dplyr::if_else() is called "Vectorised if" in the documentation.

It's if ... else clauses which are not vectorised.

if_else() is strict about what it allows. I'm sure it has its uses but I find it too strict on occasions.

This topic was automatically closed 7 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.