【问题标题】:Extract the maximum value within each group in a dataframe [duplicate]提取数据框中每个组内的最大值[重复]
【发布时间】:2014-10-08 11:25:21
【问题描述】:

我有一个带有分组变量(“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 可以解决问题吗?

【问题讨论】:

  • 是的。 aggregate 可以解决问题。只需使用max 作为相关函数即可。

标签: r aggregate


【解决方案1】:

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

【讨论】:

  • 您可以将 dplyr 添加到集合中 (+1)
  • 而且,aggregate 的公式方法提供了更好的输出...
  • 这应该是一个 SO R wiki Q/A
  • @beginneR:我还没有使用过 dplyr(我更像是一个 data.table-guy),但很容易找到。
  • @AnandaMahto:还添加了 aggregate.formula...
【解决方案2】:
df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))

只使用基础 R

【讨论】:

    【解决方案3】:

    使用 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 包用于函数的 groupby 应用程序(最大) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize

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

    【讨论】:

    • 是否可以在一个命令行中获取最大值和最小值(或它们之间的差异)?
    • hmm 看起来我可以使用:aggregate(na.omit(Value)~Gene, df, function(x) c(max(x)-min(x)))
    猜你喜欢
    • 2020-11-11
    • 2018-10-10
    • 2017-09-12
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多