6

如果我有以下数据框:

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

我怎样才能获得每个因子A的最高值以及与它相关的因子B的条目,即

value   factorA factorB

3         a        g
3         b        m
2         c        g

不先使用这可能吗

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

然后对每个 block$a 进行排序,因为这将执行多次,并且块的数量总是会改变。

4

2 回答 2

12

这是一种选择,使用基本 R 函数:

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
于 2012-04-10T18:35:18.560 回答
4

使用您的数据

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))

使用包ddply中的函数plyr

> 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

或者,

> rownames(df2) <- df2$factorA
> df2
  value factorA factorB
a     3       a       g
b     3       b       m
c     2       c       g
于 2012-04-10T19:57:24.280 回答