【问题标题】:Find the max and min value within each group [duplicate]找到每组中的最大值和最小值[重复]
【发布时间】:2018-03-09 13:53:50
【问题描述】:

我想在下表中找到每个基因的最大值和最小值。 我知道,以下函数给出了最大值(或最小值),但我无法同时获得两者。

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

欣赏!

小测试集:

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

【问题讨论】:

  • 试试library(dplyr);df %&gt;% group_by(Gene) %&gt;% summarise(Min = min(Value), Max = max(Value))
  • range(x) 返回一个二元素向量,其最小值和最大值为x
  • tapply(df$Value, df$Gene, FUN = function(x) c(max = max(x), min = min(x)))?
  • aggregate(Value ~ Gene, data=df, FUN=range)

标签: r


【解决方案1】:
range()

是同时返回最大值和最小值的函数

你会这样做:

tapply(df$Value, df$Gene, range)

# $A
# [1]   1 123

# $B
# [1] 3 6

# $C
# [1] 1 1

# $D
# [1]   3 234

【讨论】:

    【解决方案2】:

    您可以继续使用tapply,只需修改FUN 参数即可返回多个汇总统计信息。例如:

    do.call(rbind, tapply(df$Value, df$Gene, FUN = function(x) c(max = max(x), min = min(x))))
    #  max min
    #A 123   1
    #B   6   3
    #C   1   1
    #D 234   3
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2018-03-12
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多