Search code examples
rdataframemax

Find the value that makes maximum in R


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.


Solution

  • 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.