Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R shortcut to getting last n entries in a vector [duplicate]

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!

like image 655
harkmug Avatar asked Feb 15 '13 19:02

harkmug


People also ask

How do I retrieve the last element of a vector in R?

To find the last element of the vector we can also use tail() function.

How do I get the last N element in a list in R?

The last n rows of the data frame can be accessed by using the in-built tail() method in R. Supposedly, N is the total number of rows in the data frame, then n <=N last rows can be extracted from the structure.

How do I index a vector in R?

Vector elements are accessed using indexing vectors, which can be numeric, character or logical vectors. You can access an individual element of a vector by its position (or "index"), indicated using square brackets. In R, the first element has an index of 1. To get the 7th element of the colors vector: colors[7] .

How do I remove data from a vector in R?

How to remove elements from vector in R? By using r base [] notation and setdiff() function is used to remove values from vector. Actually by using [] notation we can select values from vector and by negative the result you can remove the selected elements.


2 Answers

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
like image 169
Dason Avatar answered Sep 18 '22 18:09

Dason


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.

like image 20
Tyler Rinker Avatar answered Sep 20 '22 18:09

Tyler Rinker