Search code examples
rdplyrany

In dplyr, mutate a logical column where any of a set of other logical columns are true


I have a data frame that looks like this:

typ1  typ2  typ3
   T     T     F
   F     F     F
   T     F     F

and I want mutate a 4th logical column determining if any of the other three are TRUE, so {T, F, T}.

mutate(isAnyType = any(typ1, typ2, typ3)) seems to be using the whole columns, when I would like to use the information per row. Any insight is appreciated.


Solution

  • We can use reduce with | to check if there are any TRUE elements in each row

    library(dplyr)
    library(purrr)
    df1 %>%
       mutate(isAnyType = reduce(., `|`))
    

    Or using rowSums in base R

    df1$isAnyType <- rowSums(df1) > 0
    

    Or another option is pmap

    df1 %>%
       mutate(isAnyType = pmap_lgl(., ~ any(c(...)))
    

    data

    df1 <- structure(list(typ1 = c(TRUE, FALSE, TRUE), typ2 = c(TRUE, FALSE, 
    FALSE), typ3 = c(FALSE, FALSE, FALSE)), class = "data.frame", 
    row.names = c(NA, 
    -3L))