Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

r - How many elements in a vector are greater than x without using a loop

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 ?

I would like to get :

2

as a result

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...