Skip to content

keep the row indexes/names when do aggregate

3 messages · zhihuali, Gabor Grothendieck, Adaikalavan Ramasamy

#
Rather than aggregate, use order and duplicated as in this post:

https://stat.ethz.ch/pipermail/r-help/2008-September/173139.html
On Wed, Sep 24, 2008 at 11:21 AM, zhihuali <lzhtom at hotmail.com> wrote:
#
Not the most elegant solution but here goes.

    df <- data.frame(g=c("g1","g2","g1","g1","g2"),v=c(1,7,3,2,8))

    rownames.which.max <- function(m, col){
                                   w <- which.max( m[ , col] )
                                   return( rownames(m)[w] )
    }

    df.split <- split(df, df$g)
    ws <- sapply( df.split, rownames.which.max, col="v" )

    ws
     g1  g2
    "3" "5"

    df[ws, ]
       g v
    3 g1 3
    5 g2 8

Regards, Adai
zhihuali wrote: