【问题标题】:Less stringent filter if_all不太严格的过滤器 if_all
【发布时间】:2023-01-19 22:00:04
【问题描述】:

有没有办法在 dplyr 的过滤函数中对几乎所有的 if_all 使用不那么严格?


#make this example reproducible
set.seed(1)

#create data frame with 10 random numbers between 1 and 20
df <- as.data.frame(matrix(runif(n=25, min=1, max=20), nrow=5))

#define column names
names(df) <- c('A.length', 'b.length','C.length','D.length','E.length')


df2<- df %>%
  filter(if_all(ends_with("length"), ~ .x >13))

> df2
[1] A.length b.length C.length D.length E.length
<0 rows> (or 0-length row.names)

我想将 if_all 设置为 if_all 但一个这样第 3 行将包含在 df2 中

【问题讨论】:

  • 请提供预期的输出 - 不太清楚您要做什么。

标签: r tidyverse


【解决方案1】:

是这样的吗?

library(tidyverse)

df %>%  
  filter(!if_any(ends_with("length"), ~ .x > 13))

# A tibble: 1 × 5
  A.length B.length C.length D.length E.length
     <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
1     2.10     10.6     3.35     6.52     2.56

【讨论】:

    【解决方案2】:

    也许 if_anyif_all 不适合你的情况。解决方法是使用 rowSums(across(...)) &gt;= n 来确定每行中值的数量 > 13 是否 >= 阈值。

    df %>%
      filter(rowSums(across(ends_with("length")) > 13) >= 4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      相关资源
      最近更新 更多