rif-statementconditional-statements

How to apply multiple conditions when using %in%?


I have this example where I wish to create the column m where if x1 or x2 or x3 = "A" or "B" then m = 1, otherwise m = 0

df <- data.frame(x1 = LETTERS[1:10], x2 = LETTERS[2:11], x3 = LETTERS[3:12])


df <-  df%>% 
   mutate(m = ifelse(df[,paste0("x",1:3)] %in% c("A","B") ,1,0))

when using this code it is not working and I don't know where the bug is and how to fix it. Thanks.


Solution

  • You can use rowSums. Better use grep instead of the paste approach.

    > df |> 
    +   transform(m=+(rowSums(sapply(df[grep('^x\\d$', names(df))], `%in%`, c('A', 'B'))) > 0))
       x1 x2 x3 m
    1   A  B  C 1
    2   B  C  D 1
    3   C  D  E 0
    4   D  E  F 0
    5   E  F  G 0
    6   F  G  H 0
    7   G  H  I 0
    8   H  I  J 0
    9   I  J  K 0
    10  J  K  L 0
    

    dplyr::mutate should also work, haven't installed it. Avoid ifelse or the like whenever possible, it's just slow.