How to extract the row with min or max values?

matteo picture matteo · Oct 18, 2013 · Viewed 85.3k times · Source

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     7.10
...
2000    P2  1997    10.5    6.90
2001    P2  1997    9.9     7.00
2002    P2  1997    10.0    6.93

if I want to know where the max value is I type:

which.max(df$Temp)

and R print the index of the row, for example 665.

So, if I want to read and extract the column with all the related values, I have to type:

df[665, ]

Isn't there a simpler way to know which ID is related to the max value of a specific column of the df?

Answer

Joshua Ulrich picture Joshua Ulrich · Oct 18, 2013

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

df[which.max(df$Temp),]