Skip to content
Prev 157066 / 398506 Next

keep the row indexes/names when do aggregate

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: