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

86

我有一个数据框,其中包含一个分组变量(“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

聚合功能能行吗?


2
是的。aggregate 可以解决问题。只需使用max 作为相关函数即可。 - A5C1D2H2I1M1N2O1R2T1
3个回答

198

在 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))),]

5
你可以将dplyr添加到这个集合中(+1)。 - talat
而且,aggregate 的公式方法可以给出更好的输出... - A5C1D2H2I1M1N2O1R2T1
@beginneR: 我还没有用过dplyr(我更多是data.table的爱好者),但是弄清楚它很容易。 - EDi
1
@AnandaMahto:还添加了aggregate.formula... - EDi
我在SO上看到的最简单和最全面的答案之一。做得好!谢谢 :)。 - theforestecologist
显示剩余6条评论

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

只使用基础的 R


1

有没有可能在一条命令行中获取最大值和最小值(或它们之间的差异)? - godines
看起来我可以使用以下代码:aggregate(na.omit(Value)~Gene, df, function(x) c(max(x)-min(x))) - godines

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接