Find value corresponding to maximum in other column [duplicate]

时光毁灭记忆、已成空白 提交于 2020-01-30 10:32:25

问题


I have a data frame similar to as follows:

x <- c(1, 2, 3, 4, 5)
y <- c(1, 2, 3, 2, 1)
df <- data.frame(x, y)

I want to find the value of x when y is at its maximum. I know that I can find the max of y with this:

max(df$y)

But I don't know how to match it, and I think there's probably a better way.


回答1:


Using 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

Alternatively to return a vector

df %>% 
    filter(x == max(y)) %>% 
    pull(x) # pull the variable y

using base R:

df[df$x == max(df$y), "x"]



回答2:


Try indexing like this:

df$x[df$x == max(y)]


来源:https://stackoverflow.com/questions/53155724/find-value-corresponding-to-maximum-in-other-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!