【问题标题】:How to select column content based on max value within groups of another column. Select marker name based of maximun value for each gene如何根据另一列的组内的最大值选择列内容。根据每个基因的最大值选择标记名称
【发布时间】:2020-06-04 19:54:07
【问题描述】:

我有以下df:

Gene pval  Marker
A      0.12     M1
A      0.11     M2
B      0.33     M3
B      0.55     M4
B      0.06     M5
D      0.03     M7
D      0.04     M8

我想根据每个基因的最大 pvalue 来获取标记名称。 我尝试过的:

peak_marker <-df[which.max(df[,2]),3]

但结果是整个数据框中 pvalue 最高的标记名称,而不是每个基因 pval 最高的标记名称。

我也试过了,但没有成功:

aggregate(df$pval, by = list(df$Gene), which.max)

【问题讨论】:

    标签: r dataframe statistics max aggregate


    【解决方案1】:

    实际上你很接近aggregate,但你可能需要merge的一些额外帮助。

    这是一个基本的 R 解决方案,其中使用了 aggregate + merge,即,

    dfout <- merge(aggregate(pval~Gene,df,max),df,all.x = T)
    

    这样

    > dfout
      Gene pval Marker
    1    A 0.12     M1
    2    B 0.55     M4
    3    D 0.04     M8
    

    数据

    df <- structure(list(Gene = c("A", "A", "B", "B", "B", "D", "D"), pval = c(0.12, 
    0.11, 0.33, 0.55, 0.06, 0.03, 0.04), Marker = c("M1", "M2", "M3", 
    "M4", "M5", "M7", "M8")), class = "data.frame", row.names = c(NA, 
    -7L))
    

    【讨论】:

      【解决方案2】:

      这里是使用basedata.table 的解决方案!

      读入数据:

      library(data.table)
      df = fread("Gene pval  Marker
      A      0.12     M1
      A      0.11     M2
      B      0.33     M3
      B      0.55     M4
      B      0.06     M5
      D      0.03     M7
      D      0.04     M8")
      setDF(df)
      

      对于base,我们基本上将遍历Gene 的每个唯一值并手动对数据进行子集化

      sapply(unique(df[,'Gene']), FUN = function(g) {
          d = df[df$Gene == g,]
          d[which.max(d[,2]),3]
      })
      #>    A    B    D 
      #> "M1" "M4" "M8"
      

      使用data.table,我们可以使用by 参数将数据分成组,然后使用.SD(它是数据的子集)访问组内的部分数据

      setDT(df)
      df[,.SD[order(-pval)][1,Marker], by = Gene]
      #>    Gene V1
      #> 1:    A M1
      #> 2:    B M4
      #> 3:    D M8
      

      【讨论】:

        【解决方案3】:

        使用dplyr的解决方案:

        library(dplyr)
        df %>% 
          group_by(Gene) %>% 
          filter(val == max(val))
        

        返回:

          # A tibble: 3 x 3
          # Groups:   Gene [3]
            Gene    val Marker
            <chr> <dbl> <chr> 
          1 A      0.12 M1    
          2 B      0.55 M4    
          3 D      0.04 M8   
        

        或者,如果我们想摆脱分组:

          df %>% 
            group_by(Gene) %>% 
            filter(val == max(val)) %>% 
            ungroup()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-29
          • 1970-01-01
          • 2021-09-12
          • 1970-01-01
          • 1970-01-01
          • 2021-05-25
          • 1970-01-01
          • 2014-10-05
          相关资源
          最近更新 更多