Skip to content

Suprising behaviour of if_any() inside case_when #5782

@iagogv3

Description

@iagogv3

I am not sure if I am doing something wrong, but If that is the case I cannot see what in next reproducible example:

data <- structure(list(x = c(1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, 
-1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 
-1, -1), y = c(-1, -1, 1, 1, 2, 1, -1, 1, 1, 1, -1, 1, 1, 1, 
1, -1, 1, -1, 1, 1, 2, -1, 1, -1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, 
-30L), class = c("tbl_df", "tbl", "data.frame"))

data %>%
    mutate(dich = case_when(if_any(c(x, y), function(.x) {.x == 1}) ~ "green",
                             x==2 | y==2 ~ "blue",
                             TRUE ~ NA_character_)) %>%
    pull(dich) %>% table(useNA = "ifany")
blue green 
    2    28 

# but

data %>%
    mutate(dich = case_when(if_any(c(x, y), function(.x) {.x == 1}) ~ "green",
                             if_any(c(x, y), function(.x) {.x == 2}) ~ "blue",
                             TRUE ~ NA_character_)) %>%
    pull(dich) %>% table(useNA = "ifany")
green  <NA> 
   28     2 

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions