R to get the last n entries in the vector

This may be redundant, but I could not find a similar question about SO.

Is there a shortcut to get the last n elements / records 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 them say that the last 7 entities are needed, 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!

+7
source share
2 answers

You need 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 simple ways to capture everything except the last / first n elements of the vector.

 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 
+13
source

Not a good idea when you have awesome tail function, but here's an alternative:

 n <- 3 rev(rev(foo)[1:n]) 

I am preparing for the voices below.

+3
source

All Articles