r语言 - 如果在一行中的任何变量中满足条件,则在dplyr中进行过滤



取下面的小数据框

df = tribble(
~col1,~col2,~col3,
1,2,3,
4,5,6,
7,8,9
)

我想过滤ANY值小于5的行。以下是我最初的想法,但行不通:

df %>%
filter(across(
.fns = ~.<5
))

然而,它的输出是

1 , 2 , 3

而不是

的预期输出
1 , 2 , 3,
4 , 5 , 6

虽然有一个不使用across()和使用filter(col1 < 5 | col2 < 5 | col3 < 5)过滤的解决方案,但我想学习一种更通用的方法,可以与all_of()everything()一起使用更大的数据集。

一个人该怎么做呢?

1)使用rowSums

df %>% filter(rowSums(. < 5) > 0)
## # A tibble: 2 x 3
##    col1  col2  col3
##   <dbl> <dbl> <dbl>
## 1     1     2     3
## 2     4     5     6

2)orReduce

df %>% filter(Reduce(`|`, as.data.frame(. < 5)))
## # A tibble: 2 x 3
##    col1  col2  col3
##   <dbl> <dbl> <dbl>
## 1     1     2     3
## 2     4     5     6

如果您只想考虑某些列,则将点替换为select(., ...whatever...)或仅使用普通下标。

3)或者使用c_across

df %>% rowwise %>% filter(any(c_across() < 5))
## # A tibble: 2 x 3
##    col1  col2  col3
##   <dbl> <dbl> <dbl>
## 1     1     2     3
## 2     4     5     6

之前我们可以使用filter_all:

library(dplyr)
df %>% filter_all(any_vars(. < 5))

然而,由于filter_all已被弃用,我们可以将Reduceacross结合使用。

df %>% filter(Reduce(`|`, across(.fns = ~. < 5)))
#   col1  col2  col3
#  <dbl> <dbl> <dbl>
#1     1     2     3
#2     4     5     6

最新更新