[R] extracting the last row of each group in a data frame

Nutter, Benjamin NutterB at ccf.org
Tue Nov 17 14:04:40 CET 2009


I usually use the following function:

last.record <- function(data, id, ..., na.last=TRUE, decreasing=FALSE){

  #*** Make vector of variables to sort by
  v <- c(id, unlist(list(...)))

  #*** Sort Data Frame
  data <- data[do.call(order,
            c(data[,v, drop=FALSE], na.last=na.last,
decreasing=decreasing)),]

  #*** Extract last record for each id
  data[!duplicated(data[,id], fromLast=TRUE),]
}


Data        Data Frame from which the record is to be extracted
Id          ID variable from which the record is to be extracted.  The
data frame is automatically
	      sorted by this variable.  May be either a character string
or an integer.
...         Names of variables (or indices) in additon to id by which
data should be sorted.
na.last     Argument passed to order().  Determines if missing values
are placed at the end
	      of the sorting.
Decreasing  Argument passed to order().  Determines if data frame is
sorted in descending
	      order.



So, in your example

> df <- data.frame(Name = c("A", "A", "A", "B", "B", "C", "D"),
                   Value = c(1, 2, 3, 4, 8, 2, 3))


> last.record(df, "Name", "Value")

> last.record(df, 1, 2)

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Hao Cen
Sent: Monday, November 16, 2009 2:43 PM
To: r-help at r-project.org
Subject: [R] extracting the last row of each group in a data frame

Hi,

I would like to extract the last row of each group in a data frame.

The data frame is as follows

Name Value
A 1
A 2
A 3
B 4
B 8
C 2
D 3

I would like to get a data frame as
Name Value
A 3
B 8
C 2
D 3

Thank you for your suggestions in advance

Jeff

______________________________________________
R-help at r-project.org 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.


===================================

P Please consider the environment before printing this e-mail

Cleveland Clinic is ranked one of the top hospitals
in America by U.S.News & World Report (2009).  
Visit us online at http://www.clevelandclinic.org for
a complete listing of our services, staff and
locations.


Confidentiality Note:  This message is intended for use\...{{dropped:13}}




More information about the R-help mailing list