我想过滤数据框以至少在至少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"))
答案 0 :(得分:7)
使用基数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
答案 1 :(得分:1)
这是使用@Ronak rowSums
和dplyr
library(dplyr)
df %>% filter(rowSums(.[1:5]>5.5)>=2)
PS:将此解决方案用于OP数据集之前,请使用colnames(df)<- paste0('X',1:5)
更改列名称,以避免出现以下错误:
错误:列
tumor
,tumor
,tumor
,tumor
必须具有唯一的名称