8

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!

harkmug
  • 2,725
  • 22
  • 26

2 Answers2

15

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
Dason
  • 60,663
  • 9
  • 131
  • 148
  • 6
    Plus one and wanted to note the nice negative indexing properties of `tail` and `head` for future searchers. You can say "Give me all but the last n elements/rows" as wel: `head(foo, -2)` – Tyler Rinker Feb 15 '13 at 19:12
  • 1
    @TylerRinker Good point - that is good info and I added it to the answer. – Dason Feb 15 '13 at 19:19
2

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

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

I'm preparing myself for the down votes.

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • 1
    +1 for clever use of of `rev`. Also avoids using length(foo). Why can't R use `len` instead of `length` like Python?! Saves 50% typing. – harkmug Feb 15 '13 at 19:29
  • I like the first one but the second one was explicitly what they were trying to avoid in the original question. – Dason Feb 15 '13 at 19:29
  • @Dason good point I removed it as the poster explicitly states their disdain for length. – Tyler Rinker Feb 15 '13 at 19:32
  • 1
    @rmk - You could always do `len <- length` if you really wanted to save typing those 3 characters every time – Dason Feb 15 '13 at 19:55