如何使用最小值或最大值提取行?

时间:2021-07-26 20:14:16

maybe a simple question, but I cannot figure out a good method to solve it. With a df like this one:

也许是一个简单的问题,但我无法找到解决它的好方法。像这样的df:

        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.

并且R打印行的索引,例如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?

有没有更简单的方法来知道哪个ID与df的特定列的最大值相关?

1 个解决方案

#1


33  

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

您可以将which.max调用作为子集调用的第一个参数:

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

#1


33  

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

您可以将which.max调用作为子集调用的第一个参数:

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