Wael
Wael

Reputation: 1800

Using any with dplyr

How can I use any in a dplyr pipeline ?

I want to extract rows with at least one TRUE.

mydata = data.frame(V1=c(FALSE,NA,FALSE,TRUE),
                    V2 = c(NA,TRUE,FALSE,TRUE),
                    V3 = c(FALSE,FALSE,FALSE,TRUE))

mydata

     V1    V2    V3
1 FALSE    NA FALSE
2    NA  TRUE FALSE
3 FALSE FALSE FALSE
4  TRUE  TRUE  TRUE

Upvotes: 0

Views: 97

Answers (3)

Ian Gow
Ian Gow

Reputation: 3535

I think you need to use rowwise and c_across if using any, but as pointed out by @akrun, the function if_any nicely combines these elements.

library(dplyr, warn.conflicts = FALSE)

mydata <- data.frame(
    V1 = c(FALSE, NA, FALSE, TRUE),
    V2 = c(NA, TRUE, FALSE, TRUE),
    V3 = c(FALSE, FALSE, FALSE, TRUE))

mydata %>%
    rowwise() %>%
    filter(any(c_across(starts_with("V")))) %>%
    ungroup()
#> # A tibble: 2 x 3
#>   V1    V2    V3   
#>   <lgl> <lgl> <lgl>
#> 1 NA    TRUE  FALSE
#> 2 TRUE  TRUE  TRUE

mydata %>% 
    filter(if_any(starts_with("V")))
#>     V1   V2    V3
#> 1   NA TRUE FALSE
#> 2 TRUE TRUE  TRUE

Created on 2021-06-25 by the reprex package (v2.0.0)

Upvotes: 3

akrun
akrun

Reputation: 887511

We can use if_any in a vectorized way

library(dplyr)
mydata %>% 
  filter(if_any(starts_with('V')))
    V1   V2    V3
1   NA TRUE FALSE
2 TRUE TRUE  TRUE

Upvotes: 3

K.RAC
K.RAC

Reputation: 233

As a specific solution to your question, try below.

x <- mydata %>% filter(V1 | V2 | V3)

Upvotes: 2

Related Questions