Home > OS >  dplyr: filter rowwise if any value is larger than
dplyr: filter rowwise if any value is larger than

Time:01-12

How can I generalize the filter expression a>10 | b>10 to all columns? Thus, the filter expression should work with any size of data frame and return the rows where at least on value is larger than 10.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- data.frame(
  a= c(1,2,3,4),
  b= c(11,1,1,1)
)

# expected output
df %>%
  rowwise %>% 
  filter(
 a > 10 | b > 10
)
#> # A tibble: 1 × 2
#> # Rowwise: 
#>       a     b
#>   <dbl> <dbl>
#> 1     1    11

Created on 2023-01-12 by the reprex package (v2.0.1)

CodePudding user response:

You can use if_any with everything() to specify all columns. These functions are from the dplyr package.

library(dplyr)

df %>% filter(if_any(everything(), ~.x > 10))

  a  b
1 1 11
  • Related