views:

2138

answers:

4

Yes people, even though I'm talking about the R Project for Statistical Computing, it can still require programming!

Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the length() function? Something ala PERL's $# special var?

So I would like something like dat$vec1$vec2[$#], instead of dat$vec1$vec2[length(dat$vec1$vec2)]

Thanks!

A: 

I am by no means an R expert, but a quick google turned up this: http://www.stat.ucl.ac.be/ISdidactique/Rhelp/library/pastecs/html/last.html

There appears to be a "last" function.

benefactual
Yes, but it's not part of the language or base package. It's in the pastecs pacakge, which is the "Package for Analysis of Space-Time Ecological Series": http://cran.r-project.org/web/packages/pastecs/
ars
+1  A: 

If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck. The standard idiom is

x[length(x)]

but it's easy enough to write a function to do this:

last <- function(x) { return( x[length(x)] ) }

This missing feature in R annoys me too!

Gregg Lind
+6  A: 

I use the tail() function:

tail(vector, n=1)

The nice thing with tail() is that it works on dataframes too, unlike the x[length(x)] idiom.

lindelof
however x[length(x[,1]),] works on dataframes orx[dim(x)[1],]
kpierce8
Note that for data frames, length(x) == ncol(x) so that's definitely wrong, and dim(x)[1] can more descriptively be written nrow(x).
hadley
+5  A: 

Combining lindelof's and Gregg Lind's ideas:

last <- function(x) { tail(x, n = 1) }

Working at the prompt, I usually omit the "n=", i.e. tail(x, 1).

Unlike last from the pastecs package, head and tail (from utils) work not only on vectors but also on data frames etc., and also can return data "without first/last n elements", e.g.

but.last <- function(x) { head(x, n = -1) }

(Note that you have to use head for this, instead of tail.)

Florian Jenn