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.
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(...)))
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))