Get Last Value of Vector in R (2 Examples)


In this R tutorial you’ll learn how to access the last value in a vector.

The article is structured as follows:

All right. So first I’m going to create some example data…


Creation of Example Data

Before we can start with the extraction of the last value of a vector, we actually need to create such a vector first:

vec <- c("A", "B", "C", "Z")   # Create example vector

Our example vector is a character string and contains the four elements A, B, C, and Z (i.e. Z is the last value of our example vector). Now, let’s extract this last element with some R code…


Access Last Value with length Function

A commonly used R function for accessing the last value of a vector or array is the length function.

The length function returns (as the name of the function indicates) the length of a data object. We can use this information to create a subset of our data containing only the last element of our data:

vec[length(vec)]               # Extract last element with length
# "Z"


Access Last Value with length Function

An alternative to length() is the tail function. The tail function returns the last x elements of some input data. By specifying the argument n = 1, we can tell the function to return only the very last value in our vector:

tail(vec, 1)                   # Extract last element with tail
# "Z"

Same RStudio console output as before – Looks good!


Video & Further Resources

I have released a video on my YouTube channel, which explains the examples of this tutorial in a live R programming session. In case you want to have a look at the video, you can find it below:



Furthermore, you might want to have a look at some other articles on this website:


I hope you learned in this tutorial how to get the last value of a vector in the R programming language. However, if you have any further questions, please let me know in the comments section below.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.