How to Select Elements from a Vector in R?

Spread the love

Problem –

You want to extract one or more elements from a vector.

Solution –

To select a vector by position, you can use square brackets. If you want to select the 4th element then you can write v[4].

> a <- c(5, 10, 15, 20, 25, 30, 35, 40, 45, 50)
> a[4]
[1] 20
> a[10]
[1] 50

In R indexing starts at 1 compared to many other programming languages where indexing starts at 0.

You can also select multiple elements at once.

> a[1:3] # select elements 1 through 3
[1]  5 10 15
> a[4:8] # select elements 4 through 8
[1] 20 25 30 35 40

An index of 1:3 means select elements 1, 2, and 3.

In R you can also use negative indexing. An index of -1 means exclude the first value and return all other values.

> a[-1]
[1] 10 15 20 25 30 35 40 45 50
> a[-4]
[1]  5 10 15 25 30 35 40 45 50

We can also use a logical vector to select elements from a vector. Whenever that logical vector is TRUE, an element gets selected.

> a < 15
 [1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> a[a<15]
[1]  5 10

Let’s say you want to select all the elements which is greater than the mean of the vector.

> a[a > mean(a)]
[1] 30 35 40 45 50

You can also select elements by name.

> prices <- c(120, 20, 60, 80)
> names(prices) <- c("Apple", "Bananas", "Orange", "Mango")
> prices
  Apple Bananas  Orange   Mango 
    120      20      60      80 
> prices['Apple']
Apple 
  120 
> prices['Mango']
Mango 
   80 
> prices[c("Bananas","Orange")]
Bananas  Orange 
     20      60 

Rating: 1 out of 5.

Posted in RTagged

Leave a Reply