查找与其他列中的最大值相对应的值

Mar*_*ayo 5 r max match correspondence

我有一个类似于如下的数据框:

x <- c(1, 2, 3, 4, 5)
y <- c(1, 2, 3, 2, 1)
df <- data.frame(x, y)
Run Code Online (Sandbox Code Playgroud)

x我想找到何时y达到最大值的值。我知道我可以用这个找到最大值y

max(df$y)

但我不知道如何搭配,我想可能有更好的方法。

Joh*_*ene 5

使用dplyr

# install.packages(dplyr)
library(dplyr)

df %>% 
    filter(x == max(y)) %>% # filter the data.frame to keep row where x is maximum
    select(x) # select column y
Run Code Online (Sandbox Code Playgroud)

或者返回一个向量

df %>% 
    filter(x == max(y)) %>% 
    pull(x) # pull the variable y
Run Code Online (Sandbox Code Playgroud)

使用基数 R:

df[df$x == max(df$y), "x"]
Run Code Online (Sandbox Code Playgroud)