一个向量中有多少元素比x大而不使用循环

时间:2022-09-25 04:17:52

If I have the following vector :

如果我有以下向量:

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

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

我想知道有多少元素大于10,我怎么才能不使用循环呢?

I would like to get :

我想要得到:

2

as a result

作为一个结果

1 个解决方案

#1


24  

Use length or sum:

使用长度或金额:

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

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.

在第一个方法中,您将创建一个向量,该向量将子设置与您的条件相匹配的值,然后检索向量的长度。

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.

在第二种方法中,您只需创建一个逻辑向量,该逻辑向量表示每个值是否与条件(TRUE)匹配或不匹配(FALSE)。既然真与假等于“1”和“0”,你可以简单地用sum来得到你的答案。

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

因为第一种方法需要在计数之前进行索引和子设置,所以我几乎可以肯定第二种方法比第一种方法要快。

#1


24  

Use length or sum:

使用长度或金额:

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

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.

在第一个方法中,您将创建一个向量,该向量将子设置与您的条件相匹配的值,然后检索向量的长度。

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.

在第二种方法中,您只需创建一个逻辑向量,该逻辑向量表示每个值是否与条件(TRUE)匹配或不匹配(FALSE)。既然真与假等于“1”和“0”,你可以简单地用sum来得到你的答案。

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

因为第一种方法需要在计数之前进行索引和子设置,所以我几乎可以肯定第二种方法比第一种方法要快。