【问题标题】:Keep min or max based on character in another column根据另一列中的字符保持最小值或最大值
【发布时间】:2021-03-16 02:48:38
【问题描述】:

我有这个:

  Genes strand mode_position
    1:   2L52.1      +          1638
    2:   2L52.1      +          2096
    3:   npr-30      +          3156
    4:   homt-1      -          6081
    5:  B0348.5      +          6383

如果有重复的基因并且立场是+,我需要保留mode_position最高值的行,如果-,则保留最低值的行。所以对于 2L52.1,它应该只保留第 2 行。 我正在尝试group_by(Genes) %>% if_else("strand" == "+", slice_max(mode_position, n=1)),但这显然不起作用,因为“条件”必须是一个逻辑向量。 case_when 对字符不起作用?还有哪些其他选择?

谢谢!

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    您可以使用if/elsewhich.maxwhich.min 来获得最大和最小行。

    library(dplyr)
    
    df %>%
      group_by(Genes) %>%
      slice(if(all(strand == '+')) which.max(mode_position) 
            else which.min(mode_position)) %>%
      ungroup
    
    #  Genes   strand mode_position
    #  <chr>   <chr>          <int>
    #1 2L52.1  +               2096
    #2 B0348.5 +               6383
    #3 homt-1  -               6081
    #4 npr-30  +               3156
    

    数据

    df <- structure(list(Genes = c("2L52.1", "2L52.1", "npr-30", "homt-1", 
    "B0348.5"), strand = c("+", "+", "+", "-", "+"), mode_position = c(1638L, 
    2096L, 3156L, 6081L, 6383L)), class = "data.frame", row.names = c(NA, -5L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-25
      • 2021-05-25
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多