在不使用循环的情况下,向量中有多少个元素大于x [英] How many elements in a vector are greater than x without using a loop

查看:95
本文介绍了在不使用循环的情况下,向量中有多少个元素大于x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下向量:

x
[1]  1  5  8  9  1  0 15 15

我想知道有多少个元素大于10,如何在不使用循环的情况下继续进行操作?

and I want to know how many elements are greater than 10, how can I proceed without using a loop ?

我想得到:

2

结果

推荐答案

使用lengthsum:

> length(x[x > 10])
[1] 2
> sum(x > 10)
[1] 2

在第一种方法中,您将创建一个向量,该向量将与您的条件相匹配的值子集化,然后检索该向量的length.

In the first approach, you would be creating a vector that subsets the values that matches your condition, and then retrieving the length of the vector.

在第二种方法中,您只是创建一个逻辑向量,该逻辑向量说明每个值是否符合条件(TRUE)或不符合条件(FALSE).由于TRUEFALSE分别等于"1"和"0",因此您只需使用sum即可获得答案.

In the second approach, you are simply creating a logical vector that states whether each value matches the condition (TRUE) or doesn't (FALSE). Since TRUE and FALSE equate to "1" and "0", you can simply use sum to get your answer.

由于第一种方法需要先进行索引和子集计数,所以我几乎可以肯定,第二种方法会比第一种更快.

Because the first approach requires indexing and subsetting before counting, I am almost certain that the second approach would be faster than the first.

这篇关于在不使用循环的情况下,向量中有多少个元素大于x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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