mercredi 2 décembre 2020

ifelse() used with all() on multiple columns

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?

Aucun commentaire:

Enregistrer un commentaire