[R] Using split and sapply to return entire lines

Gabor Grothendieck ggrothendieck at gmail.com
Wed Nov 9 06:57:02 CET 2005


On 11/9/05, Todd A. Gibson <tgibson at augustcouncil.com> wrote:
> On Tue, Nov 08, 2005 at 10:47:26PM -0500, Gabor Grothendieck wrote:
> > Also, one can use aggregate:
> >
> > aggregate(DF[,-1], list(month = DF$month), max)
>
> The issue here is that I need the row corresponding to the month with
> the maximum length.  That is, aggregate(.) is returning both the
> maximum month and maximum ratio for all rows with month=Jan.  I need
> the single row in month=Jan which has the maximum length.

Try this to calculate the index, idx, of the largest in each group
and then put it all together in the last line:

f <- function(x) rownames(x)[which.max(x$length)]
idx <- by(DF, DF$month, f)
cbind(index = c(idx), DF[idx,])




More information about the R-help mailing list