Find the value that makes maximum in R

Viewed 74

Here I made a simple data df to demonstrate what I want to do.

df<-data.frame(id=c(2,3,6,8,12,34,27),
               points=c(2,3,5,9,19,2,3))

My goal is to find the id that has the maximum points. In my example, 19 is the maximum points, so the corresponding id is 12. In my example, the answer is trivial. But,I want to find id that maximizes the points using simple R code.

5 Answers

Here are three ways:

# Base R
df[df$points==max(df$points), "id"]

# dplyr
library(dplyr)
df  |>
    filter(points==max(points))  |>
    pull(id)

# data.table
library(data.table)
setDT(df)

df[points==max(points), id]

The output to all of these is 12.

We can use which.max in base R

with(df, id[which.max(points)])
[1] 12

Here is another strategy:

df %>% 
  arrange(-points) %>% 
  slice(1) %>% 
  pull(id)
12

We can use order in base R

> with(df, id[order(-points)][1])
[1] 12

There is also slice_max() in dplyr.

df %>% 
  slice_max(points)
Related