Search code examples
rdplyrsubsetboolean-logic

Boolean expression - if 2 or more conditions True


I'm trying to create a dplyr filter based on some conditions, say there are three conditions, condition1, condition2 and condition3. I want it to evaluate overall as TRUE if ANY two or more conditions are TRUE,

Any idea how to do this easily in R? I can make a very long expression with each combination of conditions, but was hoping for something easier,

Many thanks

EDIT:

Reprex as requested

df %>%
filter(condition1|condition2|condition2)

I want the subset of df where two or greater of the conditions above are true


Solution

  • Here's a dplyr approach. You can also use rowwise and c_across if you want to be strictly tidyverse-y about it.

    library(dplyr)
    
    df <- tibble(a = c(T, T, F), b = c(F, T, T), c = c(T, F, F))
    
    df
    # A tibble: 3 x 4
      a     b     c     truth_ct
      <lgl> <lgl> <lgl>    <dbl>
    1 TRUE  FALSE TRUE         2
    2 TRUE  TRUE  FALSE        2
    3 FALSE TRUE  FALSE        1
    
    df %>% 
      mutate(truth_ct = rowSums(.)) %>% 
      filter(truth_ct >= 2)
    
    # A tibble: 2 x 4
      a     b     c     truth_ct
      <lgl> <lgl> <lgl>    <dbl>
    1 TRUE  FALSE TRUE         2
    2 TRUE  TRUE  FALSE        2
    

    rowwise approach:

    df %>% 
      rowwise() %>% 
      mutate(truth_ct = sum(c_across(a:c))) %>% 
      filter(truth_ct >= 2)