To get the last N items from a vector in R, you can use array indexing in combination with the `length` function.
In this example,
# Define a vector containing elements
vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Specify the number of items to retrieve (N)
N <- 5
# Calculate the starting index for the last N items
start_index <- length(vector) - N + 1
# Retrieve the last N items from the vector
last_N_items <- vector[start_index:length(vector)]
# Print the last N items
print(last_N_items)
[6, 7, 8, 9, 10]
In this example,
# Define a character vector
char_vector <- c("apple", "banana", "orange", "grape", "kiwi")
# Calculate the starting index for the last three items
start_index <- length(char_vector) - 2
# Retrieve the last three items from the character vector
last_three_items <- char_vector[start_index:length(char_vector)]
# Print the last three items
print(last_three_items)
[orange, grape, kiwi]
In this tutorial, we learned How to get Last N Items from a Vector in R language with well detailed examples.