在R中,如何根据数据每一行中的最大值进行过滤? [英] In R, how can I filter based on the maximum value in each row of my data?
问题描述
我有一个小标题(或数据框,如果您愿意的话),它是19列纯数值数据,我想将其过滤为仅至少一个值大于或小于阈值的行。我更喜欢tidyverse / dplyr解决方案,但无论如何都可以。
I have a tibble (or data frame, if you like) that is 19 columns of pure numerical data and I want to filter it down to only the rows where at least one value is above or below a threshold. I prefer a tidyverse/dplyr solution but whatever works is fine.
This is related to this question but a distinct in at least two ways that I can see:
- 我没有标识符列(我想应该是行号除外)
- 我需要基于正在评估当前行,而不是跨列
以下是我尝试过的尝试:
Here are attempts I've tried:
data %>% filter(max(.) < 8)
data %>% filter(max(value) < 8)
data %>% slice(which.max(.))
推荐答案
这是一种将行的值保持在阈值以上的方法。为了将值保持在阈值以下,只需反转 any
-
Here's a way which will keep rows having value above threshold. For keeping values below threshold, just reverse the inequality in any
-
data %>%
filter(apply(., 1, function(x) any(x > threshold)))
实际上,@ r2evans在评论中的回答更好-
Actually, @r2evans has better answer in comments -
data %>%
filter(rowSums(. > threshold) >= 1)
这篇关于在R中,如何根据数据每一行中的最大值进行过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!