VOOZH about

URL: https://www.geeksforgeeks.org/r-language/access-the-last-value-of-a-given-vector-in-r/

⇱ Access the last value of a given vector in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Access the last value of a given vector in R

Last Updated : 23 Jul, 2025

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.

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:

Output:

[1] 5

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

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.

Output:

123 124 125 126 128

We 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.

Output:

126
Comment

Explore