rdataframesorting

Finding the row number based on minimum of multiple columns in a data frame


Sample data:

dat = data.frame('a' = c(4,5,6,8,2,2, 5), 'b' = c(23, 45, 12, 11, 1, 3, 4))

Now I would like to find the row number which contains the minimum value based on the columns a and b, where set priority should be a > b.

Desired result: For a, rows 5 and 6; for b, 5, therefore gloablly row 5.

Is there any method available for data frames to perform such calculation?


Solution

  • A {tidyverse} option would be dplyr::slice_min:

    library(dplyr, warn = FALSE)
    
    dat |> 
      tibble::rowid_to_column() |> 
      slice_min(tibble(a, b), n = 1)
    #>   rowid a b
    #> 1     5 2 1
    

    or if you are just interested in the row index you can use an additional pull:

    dat |> 
      tibble::rowid_to_column() |> 
      slice_min(tibble(a, b), n = 1) |> 
      pull(rowid)
    #> [1] 5