当所有列都大于一个值时过滤行 [英] filter rows when all columns greater than a value

查看:35
本文介绍了当所有列都大于一个值时过滤行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想对所有列值均符合临界值的行进行子集化。

I have a data frame and I would like to subset the rows where all columns values meet my cutoff.

以下是数据框:

   A B C
1  1 3 5
2  4 3 5
3  2 1 2

什么我想选择所有列均大于2的行。
第二行是我想要的。

What I would like to select is rows where all columns are greater than 2. Second row is what I want to get.

[1] 4 3 5

这是我的代码:

 subset_data <- df[which(df[,c(1:ncol(df))] > 2),]

但我的代码未应用在所有列上。
您知道如何解决此问题。

But my code is not applied on all columns. Do you have any idea how can I fix this.

推荐答案

我们可以创建一个逻辑矩阵,将整个数据帧与2进行比较,然后执行 rowSums 并仅选择其值等于 df

We can create a logical matrix my comparing the entire data frame with 2 and then do rowSums over it and select only those rows whose value is equal to number of columns in df

df[rowSums(df > 2) == ncol(df), ]

#  A B C
#2 4 3 5






A dplyr 使用 filter_all all_vars

library(dplyr) 
df %>%
 filter_all(all_vars(. > 2))

#  A B C
#1 4 3 5






应用 方法

df[apply(df > 2, 1, all), ]

这篇关于当所有列都大于一个值时过滤行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆