Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

r

vector

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

like image 829
Henri Avatar asked Mar 08 '13 16:03

Henri


People also ask

How do I extract elements from a vector in R?

Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.

How do I select a number from a vector in R?

The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.

How do I find the size of a vector in R?

Vectors are dimensionless in R, they have length. If one wants to consider a vector as a dimensioned object (and later work on that vector), s/he must use t() (transpose) (that in essence makes it 1-dimensional array).


1 Answers

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.

like image 145
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 21 '22 02:10

A5C1D2H2I1M1N2O1R2T1