Re: [R] unique, but keep LAST occurence

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Tue 25 Jul 2006 - 03:14:23 EST

On Mon, 2006-07-24 at 12:00 -0500, davidr@rhotrading.com wrote:
> ?unique says
>
> Value:
>
> An object of the same type of 'x'. but if an element is equal to
> one with a smaller index, it is removed.
>
> However, I need to keep the one with the LARGEST index.
> Can someone please show me the light?
> I thought about reversing the row order twice, but I couldn't get it to work right
>
> (My data frame has 125000 rows and 7 columns,
> and I'm 'uniqueing' on column #1 (chron) only, although the class of the column may not matter.)
>
> Say, e.g.,
> > DF <- data.frame(t = c(1,2,3,1,4,5,1,2,3), x = c(0,1,2,3,4,5,6,7,8))
>
> I would like the result to be (sorted as well)
> t x
> 1 6
> 2 7
> 3 8
> 4 4
> 5 5
>
> If I got the original rownames, that would be a bonus (for debugging.)

Does this get it?

> DF[sapply(unique(DF$t), function(x) max(which(DF$t == x))), ]
  t x
7 1 6
8 2 7
9 3 8
5 4 4
6 5 5

HTH, Marc Schwartz



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue Jul 25 03:24:00 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 25 Jul 2006 - 04:21:52 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.