簡體   English   中英

過濾具有X列數且值大於Y的行

[英]filter rows that have X number of columns with value greater than Y

我想過濾數據框以至少在至少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"))

使用base 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

這是使用@Ronak rowSumsdplyr另一種解決方案

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

PS:將此解決方案與OP數據集一起使用之前,請使用colnames(df)<- paste0('X',1:5)更改列名稱,以避免出現以下錯誤:

錯誤: tumortumortumortumor必須具有唯一的名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM