R shortcut to getting last n entries in a vector
arrays, indexing, r, vector
Solution
You want the `tail` function
foo <- 1:23
tail(foo, 5)
#[1] 19 20 21 22 23
tail(foo, 7)
#[1] 17 18 19 20 21 22 23
x <- 1:3
# If you ask for more than is currently in the vector it just
# returns the vector itself.
tail(x, 5)
#[1] 1 2 3
Along with `head` there are easy ways to grab everything except the last/first n elements of a vector as well.
x <- 1:10
# Grab everything except the first element
tail(x, -1)
#[1] 2 3 4 5 6 7 8 9 10
# Grab everything except the last element
head(x, -1)
#[1] 1 2 3 4 5 6 7 8 9
Problem
This may be redundant but I could not find a similar question on SO. Is there a shortcut to getting the last n elements/entries in a vector or array without using the length of the vector in the calculation? `foo <- 1:23` ``` > foo [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ``` Let say one wants the last 7 entities, I want to avoid this cumbersome syntax: ``` > foo[(length(foo)-6):length(foo)] [1] 17 18 19 20 21 22 23 ``` Python has `foo[-7:]`. Is there something similar in R? Thanks!