I have this data:
library(tidyverse)
data <- tribble(
~a, ~b , ~c , ~d,
0, 0, 0, 0,
1, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 1
)
and would like to get this output - if there is a zero in all columns TRUE
is returned:
# A tibble: 4 x 5
a b c d new
<dbl> <dbl> <dbl> <dbl> <lgl>
1 0 0 0 0 TRUE
2 1 1 0 0 FALSE
3 0 1 0 0 FALSE
4 0 0 0 1 FALSE
I tried this and it works:
data %>%
rowwise() %>%
mutate(new = ifelse(all(c(a,b,c,d) == 0) , TRUE, FALSE))
But what if I have many more columns? I would NOT want to write something like this:
data %>%
rowwise() %>%
mutate(new = ifelse(all(c(a,b,c,d,e,f,.......z) == 0) , TRUE, FALSE))
Is there a better way of writing this?
Note: I am using dplyr 0.8.3
!do.call(pmax, data)
– d.ball
returns length 1, soifelse
is a waste here; just donew = +all(...)
. (2), as @d.b just said, you can expand withdo.call
for varying number of columns (and likely withoutrowwise
, which can be horrible performance). – r2evansc_across
:data %>% rowwise() %>% mutate(new = all(c_across() == 0))
– Ronak Shah