具有 (1) ALL 和 (2) ANY 列大于特定值的子集行 [英] subset rows with (1) ALL and (2) ANY columns larger than a specific value
问题描述
我有一个带有 id 列的数据框和一些(可能很多)带有值的列,这里是v1"、v2":
I have a data frame with an id column and some (potentially many) columns with values, here 'v1', 'v2':
df <- data.frame(id = c(1:5), v1 = c(0,15,9,12,7), v2 = c(9,32,6,17,11))
# id v1 v2
# 1 1 0 9
# 2 2 15 32
# 3 3 9 6
# 4 4 12 17
# 5 5 7 11
如何提取所有值都大于某个值的行,比如 10,应该返回:
How can I extract rows where ALL values are larger than a certain value, say 10, which should return:
# id v1 v2
# 2 2 15 32
# 4 4 12 17
如何提取任何(至少一个)值大于 10 的行:
How can I extract rows with ANY (at least one) value is larger than 10:
# id v1 v2
# 2 2 15 32
# 4 4 12 17
# 5 5 7 11
推荐答案
分别查看函数 all()
和 any()
以了解问题的第一部分和第二部分.apply()
函数可用于在行或列上运行函数.(MARGIN = 1
是行,MARGIN = 2
是列,等等).注意我在 df[, -1]
上使用 apply()
以在进行比较时忽略 id
变量.
See functions all()
and any()
for the first and second parts of your questions respectively. The apply()
function can be used to run functions over rows or columns. (MARGIN = 1
is rows, MARGIN = 2
is columns, etc). Note I use apply()
on df[, -1]
to ignore the id
variable when doing the comparisons.
第 1 部分:
> df <- data.frame(id=c(1:5), v1=c(0,15,9,12,7), v2=c(9,32,6,17,11))
> df[apply(df[, -1], MARGIN = 1, function(x) all(x > 10)), ]
id v1 v2
2 2 15 32
4 4 12 17
第 2 部分:
> df[apply(df[, -1], MARGIN = 1, function(x) any(x > 10)), ]
id v1 v2
2 2 15 32
4 4 12 17
5 5 7 11
要查看发生了什么,x >10
为每一行返回一个逻辑向量(通过 apply()
指示每个元素是否大于 10.all()
返回 TRUE
如果输入向量的 all 元素为 TRUE
和 FALSE
否则.any()
返回 如果输入中的任何元素为
,如果所有元素为TRUE
,则为TRUEFALSE
,则为FALSE
.
To see what is going on, x > 10
returns a logical vector for each row (via apply()
indicating whether each element is greater than 10. all()
returns TRUE
if all element of the input vector are TRUE
and FALSE
otherwise. any()
returns TRUE
if any of the elements in the input is TRUE
and FALSE
if all are FALSE
.
然后我使用由 apply()
调用产生的逻辑向量
I then use the logical vector resulting from the apply()
call
> apply(df[, -1], MARGIN = 1, function(x) all(x > 10))
[1] FALSE TRUE FALSE TRUE FALSE
> apply(df[, -1], MARGIN = 1, function(x) any(x > 10))
[1] FALSE TRUE FALSE TRUE TRUE
子集df
(如上所示).
这篇关于具有 (1) ALL 和 (2) ANY 列大于特定值的子集行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!