Skip to content
Prev 200460 / 398503 Next

extracting the last row of each group in a data frame

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