add column based on multiple conditions with mutate() in tidy R grep

You can try using reduce from purrr package. One may use an intermediate function any_cols to made the code clearer and use it with across:

library(tidyverse)
any_cols <- function(df) reduce(df, `|`)
df %>%
    mutate(ZOO = ifelse(any_cols(across(contains("zoo"), ~`>`(.,0))), "zoo", "F"))
  elephant_zoo rhino_zoo hippo_zoo elephant_wild_A rhino_wild_A elephant_wild_B rhino_wild_C hippo_wild_B ZOO
1            1         1         1               0            0               0            0            0 zoo
2            1         2         1               0            0               0            0            0 zoo
3            1         3         0               1            4               0            1            0 zoo
4            2         1         0               1            3               0            5            0 zoo
5            0         0         0               3            1               0            7            0   F

df %>%
    mutate(ZOO = 
             case_when(any_cols(across(contains("zoo"), ~`>`(.,0))) ~ "zoo", 
                       TRUE ~ "F"))
  elephant_zoo rhino_zoo hippo_zoo elephant_wild_A rhino_wild_A elephant_wild_B rhino_wild_C hippo_wild_B ZOO
1            1         1         1               0            0               0            0            0 zoo
2            1         2         1               0            0               0            0            0 zoo
3            1         3         0               1            4               0            1            0 zoo
4            2         1         0               1            3               0            5            0 zoo
5            0         0         0               3            1               0            7            0   F

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top