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

cls59 chuck at sharpsteen.net
Mon Nov 16 20:57:24 CET 2009



jeffc wrote:
> 
> 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
> 

Try using the base function by() or ddply() from Hadley Wickham's plyr
package:

  require( plyr )

  tstData <- structure(list(Name = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 4L),
.Label = c("A", 
"B", "C", "D"), class = "factor"), Value = c(1L, 2L, 3L, 4L, 
8L, 2L, 3L)), .Names = c("Name", "Value"), class = "data.frame", row.names =
c(NA, 
-7L))

  lastRows <- ddply( tstData, 'Name', function( group ){

    return(
      data.frame( Value = tail( group[['Value']], n = 1 ) )
    )

  })

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


Hope this helps!


-Charlie


-----
Charlie Sharpsteen
Undergraduate
Environmental Resources Engineering
Humboldt State University
-- 
View this message in context: http://old.nabble.com/extracting-the-last-row-of-each-group-in-a-data-frame-tp26378194p26378404.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list