To slice the last N elements from a list in R, you can use negative index-based subsetting.
In this example,
numbers
with integer values.numbers[(length(numbers) - n + 1):length(numbers)]
to slice the last N elements.numbers <- c(1, 2, 3, 4, 5)
n <- 3
sliced_numbers <- numbers[(length(numbers) - n + 1):length(numbers)]
cat('Sliced list:', sliced_numbers)
Sliced list: 3 4 5
In this example,
words
with string values.words[(length(words) - n + 1):length(words)]
to slice the last N elements.words <- c('apple', 'banana', 'cherry', 'date', 'elderberry')
n <- 2
sliced_words <- words[(length(words) - n + 1):length(words)]
cat('Sliced list:', sliced_words)
Sliced list: date elderberry
In this tutorial, we learned How to Slice Last N Elements from a List in R language with well detailed examples.