[R] Select the last two rows by id group

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Tue Mar 20 16:33:45 CET 2007


Here is yet another solution. This one uses by() which generates nice 
visual output.

score <- data.frame(
  id      = c('001','001','001','002','003','003'),
  math    = c(80,75,70,65,65,70),
  reading = c(65,70,88,NA,90,NA)
)

out <- by( score, score$id, tail, n=2 )
# score$id: 001
#    id math reading
# 2 001   75      70
# 3 001   70      88
# ------------------------------------------------------------
# score$id: 002
#    id math reading
# 4 002   65      NA
# ------------------------------------------------------------
# score$id: 003
#    id math reading
# 5 003   65      90
# 6 003   70      NA


And if you want to put it back into a data frame, use

do.call( "rbind", as.list(out) )
#        id math reading
# 001.2 001   75      70
# 001.3 001   70      88
# 002   002   65      NA
# 003.5 003   65      90
# 003.6 003   70      NA

Ignore the rownames here.

HTH, Adai


Lauri Nikkinen wrote:
> Hi R-users,
> 
> Following this post http://tolstoy.newcastle.edu.au/R/help/06/06/28965.html ,
> how do I get last two rows (or six or ten) by id group out of the data
> frame? Here the example gives just the last row.
> 
> Sincere thanks,
> Lauri
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.
> 
> 
>



More information about the R-help mailing list