To get a last value of a vector in R, you can use the “length()” function or “tail()” function.
Method 1: Using the length() function
Syntax
length(x)
Parameter
x: It is a vector.
Example
# Define the vector
main_vector <- c(11, 21, 18, 46, 19)
# Access the last value of the vector
last_element <- main_vector[length(main_vector)]
# Print the last value
print(last_element)
Output
[1] 19
In this example, main_vector is a vector containing the integers 1, 3, 5, 7, and 9. The length() function returns the number of elements in the vector, which is 5.
By using this value as an index, you can access the last element of the vector. The last_element variable will be assigned the value 19, the last element in main_vector.
Method 2: Using the tail() function
Syntax
tail(x, n)
Parameters
- x: It is a data frame.
- n: The number of rows to be displayed.
Example
# Define the vector
main_vector <- c(11, 21, 18, 46, 19)
# Access the last value of the vector
last_element <- tail(main_vector, 1)
# Print the last value
print(last_element)
Output
[1] 19
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.