How to get rows with min values in one column, grouped by other column, while keeping other columns?

前端 未结 2 1010
轻奢々
轻奢々 2021-01-22 08:53

I have the following data:

df <- data.frame(A = c(1,2,3,4,5,6), B=c(\"P\",\"P\",\"P\",\"Q\",\"Q\",\"Q\"), C=c(\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"))
df
##              


        
相关标签:
2条回答
  • 2021-01-22 09:31

    You can try

    library(dplyr)
    df %>% 
        group_by(B) %>%
        filter(A==min(A))
    #  A B C
    #1 1 P a
    #2 4 Q d
    

    Or

    library(data.table)
    setDT(df)[, .SD[A==min(A)], B]
    

    Or using base R

     df[with(df, ave(A, B, FUN=min)==A),]
     #  A B C
     #1 1 P a
     #4 4 Q d
    
    0 讨论(0)
  • 2021-01-22 09:36

    you can also use the split-apply technique:

    # split `df` on the field 'b' 
    tmp <- split(df,df$B)
    
    # reduce to the row with the minimum value of A
    tmp  <-  lapply(tmp,function(x)
                    x[x$A == min(x$A),])
    
    # bind the rows together
    do.call(rbind,tmp)
    
    
    #>   A B C
    #> P 1 P a
    #> Q 4 Q d
    
    0 讨论(0)
提交回复
热议问题