# Access the last value of a given vector in R

In this article, we will discuss how to access the last value of a given vector in R Programming Language. So let’s begin by first creating an example vector because to get the last value of a vector we need to first create the vector.

## R

`vec1 <- ` `c` `(` `"John"` `, ` `"Smith"` `, ` `"Tina"` `, ` `"Brad"` `, ` `"Emma"` `)` `print` `(vec1)` |

**Output:**

"John" "Smith" "Tina" "Brad" "Emma"

Our first vector is a character string with some names, now we have to extract the last name from this vector.

**Method 1: Using length function**

To do this task we can use the **length()** function from the R Language. This not only enables to find out the length of the string but also access to the elements.

Syntax:length(x)

Parameter:x: vector

**Example:**

## R

`vec1 <- ` `c` `(` `"John"` `, ` `"Smith"` `, ` `"Tina"` `, ` `"Brad"` `, ` `"Emma"` `)` `length` `(vec1)` |

**Output:**

[1] 5

Now, let’s use **length() **function to get the last element of the vector:

## R

`vec1 <- ` `c` `(` `"John"` `, ` `"Smith"` `, ` `"Tina"` `, ` `"Brad"` `, ` `"Emma"` `)` `length` `(vec1)` ` ` `# To Extract last element with length` `vec1[` `length` `(vec1)]` |

**Output:**

[1] 5 [1] "Emma"

### Method 2: Using Tail() function

To find the last element of the vector we can also use **tail()** function.

Again to demonstrate it let’s first create an example vector.

## R

`vec2 <- ` `c` `(123 , 124 , 125 , 126, 128)` `print` `(vec2)` |

**Output:**

123 124 125 126 128

W have an example vector, and we have to access its last element.

Syntax:tail()

Parameters:

- x: data frame
- n: number of rows to be displayed

Here we are passing n=1 so that it will display only the last element in the vector.

## R

`vec2 <- ` `c` `(123 , 124 , 125 , 126)` `tail` `(vec2 , 1)` |

**Output:**

126