Finding a top value in dataframe

I currently have a dataframe such as
[1, ], [2, ], [3, ]
[1, ] .5 9 3
[2, ] .10 2 2
[3, ] .15 8 1

I would like to find top n values in column 2 which are 9 and 8. Additional to that, I would like to get an output which prints correspondent value in column 1 which are 0.5 and 1.5.

I have tried which.max but that only returns only 1 top value. Any idea?

Hi!

dplyr::slice_max works well for such tasks. You can use it like this:

library("dplyr")
mydf<-data.frame(a=c(0.5,0.1,0.15),
                 b=c(9,2,8),
                 c=c(3,2,1))
mydf
#      a b c
# 1 0.50 9 3
# 2 0.10 2 2
# 3 0.15 8 1

mydf%>%slice_max(b,n=2)
#      a b c
# 1 0.50 9 3
# 2 0.15 8 1

There you can even specify how ties are handled (with_ties=TRUE/FALSE).

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.