【问题标题】:Filter rows that contain specific boolean value in any column in a dataframe in R在 R 中的数据框中的任何列中过滤包含特定布尔值的行
【发布时间】:2021-03-09 14:15:51
【问题描述】:

假设我有一个数据框:

data <- data.frame(w = c(1, 2, 3, 4), x = c(F, F, F, F), y = c(T, T, F, T), 
                   z = c(T, F, F, T), z1 = c(12, 4, 5, 15))

data
#>   w     x     y     z z1
#> 1 1 FALSE  TRUE  TRUE 12
#> 2 2 FALSE  TRUE FALSE  4
#> 3 3 FALSE FALSE FALSE  5
#> 4 4 FALSE  TRUE  TRUE 15

问题

如何过滤所有布尔变量为FALSE 的行?在这种情况下,row 3。 或者换句话说,我想得到一个每行至少有 一个 TRUE 值的数据框。

预期输出

#>   w     x     y     z z1
#> 1 1 FALSE  TRUE  TRUE 12
#> 2 2 FALSE  TRUE FALSE  4
#> 3 4 FALSE  TRUE  TRUE 15

尝试

library(tidyverse)
data %>% filter(x == T | y == T | z == T)

#>  w     x    y     z z1
#> 1 1 FALSE TRUE  TRUE 12
#> 2 2 FALSE TRUE FALSE  4
#> 3 4 FALSE TRUE  TRUE 15

以上是一个可行的选项,但根本不可扩展。使用dplyr's filter()函数有没有更方便的选择?

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    rowSums() 是一个不错的选择 - TRUE 为 1,FALSE 为 0。

    cols = c("x", "y", "z")
    
    ## all FALSE
    df[rowSums[cols] == 0, ]
    
    ## at least 1 TRUE
    df[rowSums[cols] >= 1, ]
    
    ## etc.
    

    对于dplyr,我会使用同样的想法:

    df %>%
      filter(
        rowSums(. %>% select(all_of(cols))) >= 1
      )
    

    【讨论】:

      【解决方案2】:

      使用 dplyr 的filter()

      library(dplyr)
      
      filter(data, (x + y + z) > 0 )
      
        w     x    y     z z1
      1 1 FALSE TRUE  TRUE 12
      2 2 FALSE TRUE FALSE  4
      3 4 FALSE TRUE  TRUE 15
      

      【讨论】:

      • OP 说这是不可扩展的。
      【解决方案3】:
      # after @Gregor Thomas's suggestion on using TRUE or FALSE
      df[!(apply(!df[, c('x', 'y', 'z')], 1, all)), ]
      
      # without rowSums
      df[!(apply(df[, c('x', 'y', 'z')] == FALSE, 1, all)), ]
      
      # with rowSums
      df[rowSums(df[, c('x', 'y', 'z')] == FALSE) != 3, ]
      #  w     x    y     z z1
      #1 1 FALSE TRUE  TRUE 12
      #2 2 FALSE TRUE FALSE  4
      #4 4 FALSE TRUE  TRUE 15
      

      【讨论】:

        猜你喜欢
        • 2020-04-28
        • 2023-03-29
        • 2019-04-11
        • 1970-01-01
        • 2019-05-25
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        相关资源
        最近更新 更多