【问题标题】:Data frame with multiple colums, from a group of same values in one column select the maximum in the other column具有多列的数据框,从一列中的一组相同值中选择另一列中的最大值
【发布时间】:2020-09-30 18:18:02
【问题描述】:

我有以下数据框:

DF <- data.frame(A=c(0.1,0.1,0.1,0.1,0.2,0.2,0.2,0.3,0.4,0.4 ), B=c(1,2,1,5,10,2,3,1,6,2), B=c(1000,50,400,6,300,2000,20,30,40,50))

我想过滤 A 中每组相等值的 DF,选择 B 中的最大值。

例如,对于 A 中的 0.1,B 中的最大值为 5。

以新的数据框结束:

A    B    C  
0.1  5    6  
0.2  10   300  
0.3  1    30  
0.4  6    40

我不确定这是使用基本 R 还是使用库来解决的问题。因为我正在考虑使用 dplyr 和 A 组。我是对的吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    有几个基本的 R 选项:

    • 使用subset + ave
    > subset(DF,as.logical(ave(B,A,FUN = function(x) x == max(x))))
        A  B B.1
    4 0.1  5   6
    5 0.2 10 300
    8 0.3  1  30
    9 0.4  6  40
    
    • 使用merge + aggregate
    > merge(aggregate(B~A,DF,max),DF)
        A  B B.1
    1 0.1  5   6
    2 0.2 10 300
    3 0.3  1  30
    4 0.4  6  40
    

    【讨论】:

      【解决方案2】:

      带有data.table 的选项,其中按“A”分组,使用which.max 获取“B”为max 的索引,用.I 包装以返回行索引。如果我们不指定或重命名,默认情况下,它返回为 'V1' 列,我们将其提取为向量以子集数据集的行

      library(data.table)
      setDT(DF)[DF[, .I[which.max(B)], A]$V1]
      

      -输出

      #     A  B B.1
      #1: 0.1  5   6
      #2: 0.2 10 300
      #3: 0.3  1  30
      #4: 0.4  6  40
      

      【讨论】:

        【解决方案3】:

        你是对的,使用 dplyr 并按 A 分组,您可以使用 slice_max()(也来自 dplyr)为每个组选择 B 中的最大值

        library(dplyr)
        
        DF %>% 
          group_by(A) %>% 
          slice_max(B) 
        

        输出:

        # A tibble: 4 x 3
        # Groups:   A [4]
              A     B     C
          <dbl> <dbl> <dbl>
        1   0.1     5     6
        2   0.2    10   300
        3   0.3     1    30
        4   0.4     6    40
        

        【讨论】:

        • slice_max(B) 没用,我不得不换成slice(which.max(B) 谢谢
        猜你喜欢
        • 1970-01-01
        • 2020-09-08
        • 2022-01-01
        • 2017-12-24
        • 2019-08-03
        • 2020-09-08
        • 2017-02-14
        • 2012-05-25
        • 2018-01-02
        相关资源
        最近更新 更多