How to extract the row with min or max values?

前端 未结 3 1687
南笙
南笙 2020-12-03 02:35

With a dataframe like this one:

        ID  Year    Temp    ph
1       P1  1996    11.3    6.80
2       P1  1996    9.7     6.90
3       P1  1997    9.8              


        
相关标签:
3条回答
  • 2020-12-03 03:24

    A (relatively new) alternative is to use slice_max (or slice_min) from the tidyverse. Using mtcars as example:

    library(tidyverse)
    mtcars %>% slice_max(mpg)
    #                 mpg cyl disp hp drat    wt qsec vs am gear carb
    # Toyota Corolla 33.9   4 71.1 65 4.22 1.835 19.9  1  1    4    1
    
    mtcars %>% slice_min(mpg)
    #                      mpg cyl disp  hp drat    wt  qsec vs am gear carb
    # Cadillac Fleetwood  10.4   8  472 205 2.93 5.250 17.98  0  0    3    4
    # Lincoln Continental 10.4   8  460 215 3.00 5.424 17.82  0  0    3    4
    

    Note that slice_max and slice_min give you all the rows, which have a max or min value in the specified column (like the call mtcars[mtcars$mpg == min(mtcars$mpg), ]. So if you only want the first row (like in the call mtcars[which.min(mtcars$mpg), ]), you need to slice once again like:

    mtcars %>% slice_min(mpg) %>% slice(1)
    #                     mpg cyl disp  hp drat   wt  qsec vs am gear carb
    # Cadillac Fleetwood 10.4   8  472 205 2.93 5.25 17.98  0  0    3    4
    

    Moreover, slice also offers a few more helper functions for common use cases like slice_head, slice_tail and slice_sample.

    0 讨论(0)
  • 2020-12-03 03:25

    You can include your which.max call as the first argument to your subsetting call:

    df[which.max(df$Temp),]
    
    0 讨论(0)
  • 2020-12-03 03:35

    You could also use a subset and max function to call the row:

    df[df$Temp == max(df$Temp),]
    
    0 讨论(0)
提交回复
热议问题