【问题标题】:filter rows that have X number of columns with value greater than Y过滤具有 X 列且值大于 Y 的行
【发布时间】:2018-08-27 06:27:23
【问题描述】:

我想过滤我的数据框以仅在至少 2 列中保留值 > 5.5 的行。

我知道dplyr 函数filter(df,columnX>5.5),但它一次只允许使用一列或几列。

df:

    structure(list(tumor = c(5.69857588735462, 5.14269655336569, 
15.5965461799242, 5.28949625542, 6.43237599127586, 5.21673785968077
), tumor = c(5.79729396999926, 5.10961482429376, 15.8339301491681, 
5.47321124082556, 6.0624492087845, 5.21740033243091), tumor = c(5.67184459054712, 
5.024088977993, 16.1659194908984, 5.20119456848026, 6.67441109230211, 
5.15023836750153), tumor = c(5.9616857066853, 5.23907758025991, 
15.2742729676712, 5.31827944648937, 6.47526325782951, 5.15926657492595
), tumor = c(5.75116456249489, 5.03195808382708, 16.0180448251626, 
5.36575242301428, 6.85603803194346, 5.18022831262029)), class = "data.frame", row.names = c("A_33_P3390097", 
"NM_178466", "GE_BrightCorner", "ENST00000396843", "NM_001166137", 
"DarkCorner"))

【问题讨论】:

  • 快速提问。上面的代码给你一个数据框了吗?
  • 试试就知道了。已编辑
  • 看起来仍然不像数据框。 dplyr 不会理解这个对象 afaik。
  • 好吧,我刚刚在丛林某处发现了 thue class 争论。下次,稍微格式化一下你的代码:)

标签: r dataframe subset


【解决方案1】:

一种使用基数 R rowSums 的简单快捷方式,我们在其中过滤超过一列中值大于 5.5 的行。

df[rowSums(df > 5.5) > 1, ]

#                    tumor     tumor     tumor     tumor     tumor
#A_33_P3390097    5.698576  5.797294  5.671845  5.961686  5.751165
#GE_BrightCorner 15.596546 15.833930 16.165919 15.274273 16.018045
#NM_001166137     6.432376  6.062449  6.674411  6.475263  6.856038

【讨论】:

    【解决方案2】:

    这是另一个使用@Ronak rowSumsdplyr 的解决方案

    library(dplyr)
    df %>% filter(rowSums(.[1:5]>5.5)>=2)
    

    PS:在使用此方案与 OP 数据集之前,请使用colnames(df)<- paste0('X',1:5) 更改列名,以避免出现以下错误:

    错误:列 tumortumortumortumor 必须具有唯一名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多