提取数据框中每个组内的最大值

时间:2014-08-14 17:45:22

标签: r aggregate r-faq

我有一个带有分组变量(“Gene”)和值变量(“Value”)的数据框:

Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4

对于我的分组变量的每个级别,我希望提取最大值。因此,结果应该是一个数据框,每个级别的分组变量有一行:

Gene   Value
A      12
B      6
C      1
D      4

aggregate可以做到这一点吗?

3 个答案:

答案 0 :(得分:123)

在R中有很多可能性。以下是其中一些:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

答案 1 :(得分:2)

使用sqldf和标准sql获取按另一个变量

分组的最大值

https://cran.r-project.org/web/packages/sqldf/sqldf.pdf

library(sqldf)
sqldf("select max(Value),Gene from df1 group by Gene")

使用优秀的Hmisc软件包进行组合应用(最大) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize

library(Hmisc)
summarize(df1$Value,df1$Gene,max)

答案 2 :(得分:1)

df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))

只使用基础R