5

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.

Marco Pastor Mayo
  • 803
  • 11
  • 25

2 Answers2

4

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"]
FloSchmo
  • 723
  • 5
  • 9
JohnCoene
  • 2,107
  • 1
  • 14
  • 31
0

Try indexing like this:

df$x[df$x == max(df$y)]
alex_555
  • 1,092
  • 1
  • 14
  • 27