Home > Enterprise >  Find the value that makes maximum in R
Find the value that makes maximum in R

Time:07-20

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.

CodePudding user response:

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.

CodePudding user response:

We can use which.max in base R

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

CodePudding user response:

Here is another strategy:

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

CodePudding user response:

There is also slice_max() in dplyr.

df %>% 
  slice_max(points)
  • Related