Vectors are a common data structure in R. We generally use vectors to store a sequence of values of the same type. In this tutorial, we will look at how to get an element by its index in a vector in R with the help of some examples.

## How to get an element by index in a vector?

Elements in a vector are indexed starting from 1. Use the `[]`

notation to get a vector element by its index in R. The following is the syntax –

# get element at index i in a vector vec[i]

It returns the element present in the vector at the ith index.

## Examples

Let’s look at some examples of extracting elements using their respective index in R. First, we will create a vector that we will be using throughout this tutorial.

# create a vector vec <- c(10, 20, 30, 40, 50) # display the vector print(vec)

Output:

[1] 10 20 30 40 50

### Get the value at an index in a vector

Let’s use the above syntax to get the value at the index 2 in the `vec`

vector.

# get element in vector at index 2 print(vec[2])

Output:

[1] 20

We get `20`

as the output, which is the value at the second index in the vector, `vec`

. Let’s now look at some more specific use-cases.

### Get the first element in a vector

Let’s get the first value in the above vector. We know that a vector is indexed starting from 1 in R. So, the first value is present at index 1. Let’s use the above syntax to get the first value.

# get the first element in the vector print(vec[1])

Output:

[1] 10

We get the first value in the above vector as `10`

.

### Get the last element in a vector

You can similarly get the last value in a vector. The last value will present at the index which is equal to the length of the vector. You can use the `length()`

function in R to get the length of a vector.

# get the last element in the vector print(vec[length(vec)])

Output:

[1] 50

Here, we first use the `length()`

function to find the length of the vector (which is the same as the index of the last element) and then use the `[]`

notation to get the value at that index. We get `50`

as the last element in the above vector.

You might also be interested in –

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**