To get the last item in a vector in R, you can use indexing with the length
function to determine the position of the last element.
In this example,
vec
with a series of numeric values.length
function to determine the total number of elements in the vector vec
.length
function returns an integer value representing the number of elements in the vector.vec[length(vec)]
.print
function.vec <- c(10, 20, 30, 40, 50)
last_item <- vec[length(vec)]
print(last_item)
[1] 50
In this example,
char_vec
with a series of string values.length
function to determine the total number of elements in the vector char_vec
.length
function returns an integer value representing the number of elements in the vector.char_vec[length(char_vec)]
.print
function.char_vec <- c("apple", "banana", "cherry", "date", "elderberry")
last_item <- char_vec[length(char_vec)]
print(last_item)
[1] "elderberry"
In this tutorial, we learned How to get Last Item in a Vector in R language with well detailed examples.