【问题标题】:Select Columns based on Values in Column根据列中的值选择列
【发布时间】:2023-03-25 01:45:01
【问题描述】:

我正在使用tidyverse 并且我知道filter 方法允许过滤具有与特定条件匹配的值的所有行,如下所示。它会过滤至少在某一列中值介于 0 和 3 之间的所有行。

filter_all(any_vars(. > 0 & .<3)) 

我怎样才能在列的基础上做同样的事情?如果我的tibble 如下所示,我想编写一个select,它返回至少一行中的值大于 4 的所有列(应该返回列 B、C)

    | A | B | C |
    -------------
    | 1 | 1 | 2 |
    | 2 | 5 | 1 |
    | 3 | 6 | 9 |

【问题讨论】:

    标签: r tidyverse tibble


    【解决方案1】:

    我们可以使用selectany

    library(dplyr)
    df1 %>%
          select_if(~ any(. > 4))
    

    -输出

    #  B C
    #1 1 2
    #2 5 1
    #3 6 9
    

    或者在新版本中使用where

    df1 %>%
        select(where(~ any(. > 4)))
    #  B C
    #1 1 2
    #2 5 1
    #3 6 9
    

    base R 中,这可以通过Filter 完成

    Filter(function(x) any(x > 4), df1)
    

    sapply

    df1[sapply(df1, function(x) any(x > 4))]
    

    colSums

    df1[colSums(df1 >4) > 0]     
    

    数据

    df1 <- data.frame(A = 1:3, B = c(1, 5, 6), C = c(2, 1, 9))
    

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2019-07-25
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      相关资源
      最近更新 更多