How to Get the Last Value of a Vector in R

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

  1. x: It is a data frame.
  2. 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.

Leave a Comment