Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find highest value within factor levels

Tags:

r

if I have the following dataframe:

value    factorA    factorB
1           a          e
2           a          f
3           a          g
1           b          k
2           b          l
3           b          m
1           c          e
2           c          g

how can I get for each factorA the highest value and the entry from factorB associated with it i.e.

value   factorA factorB

3         a        g
3         b        m
2         c        g

Is this possible without first using

blocks<-split(factorA, list(), drop=TRUE)

and then sorting each block$a as this will be performed many times and number of blocks will always change.

like image 296
user1322296 Avatar asked Apr 10 '12 18:04

user1322296


2 Answers

Here is one option, using base R functions:

maxRows <- by(df, df$factorA, function(X) X[which.max(X$value),])
do.call("rbind", maxRows)
#   value factorA factorB
# a     3       a       g
# b     3       b       m
# c     2       c       g
like image 62
Josh O'Brien Avatar answered Oct 17 '22 06:10

Josh O'Brien


With your data

df<- structure(list(value = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L), factorA = structure(c(1L, 
        1L, 1L, 2L, 2L, 2L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"), 
            factorB = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 3L), .Label = c("e", 
            "f", "g", "k", "l", "m"), class = "factor")), .Names = c("value", 
        "factorA", "factorB"), class = "data.frame", row.names = c(NA, 
        -8L))

Using ddply function in plyr package

> df2<-ddply(df,c('factorA'),function(x) x[which(x$value==max(x$value)),])
  value factorA factorB
1     3       a       g
2     3       b       m
3     2       c       g

Or,

> rownames(df2) <- df2$factorA
> df2
  value factorA factorB
a     3       a       g
b     3       b       m
c     2       c       g
like image 4
Stat-R Avatar answered Oct 17 '22 08:10

Stat-R