How to extract the row with min or max values?

2020-01-29 07:20发布

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?

标签: r max min
2条回答
Evening l夕情丶
2楼-- · 2020-01-29 07:58

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

df[which.max(df$Temp),]
查看更多
欢心
3楼-- · 2020-01-29 08:10

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

df[df$Temp == max(df$Temp),]
查看更多
登录 后发表回答