Search code examples
rdplyrconditional-statementsmutate

mutate and if_any with condition over multiple columns


I tried to combine mutate, case_when and if_any to create a variable = 1 if any of the variables whose name begins with "string" is equal to a specific string. I can't figure out what I'm missing in the combination of these conditions.

I'm trying:

df <-data.frame(string1= c("a","b", "c"), string2= c("d", "a", "f"), string3= c("a", "d", "c"), id= c(1,2,3))

df <- df%>% 
      mutate(cod = case_when(if_any(starts_with("string") == "a" ~1 )))

Solution

  • The syntax was slightly wrong, but you were close. Note that if_any works like across, so like this if_any(columns, condition), and you should use function, \ or ~ to specify the condition.

    df %>% 
      mutate(cod = case_when(if_any(starts_with("string"), ~ .x == "a") ~ 1))
    
      string1 string2 string3 id cod
    1       a       d       a  1   1
    2       b       a       d  2   1
    3       c       f       c  3  NA