After grouping a dataframe by a categorical value, can the R function top_n break ties using a second metric column?

Viewed 18

My issue

I have a situation where I need to group by a categorical column, and then select the top items based on a scoring metric. I have been using top_n from dplyr, but it doesn't handle ties and results in a really long list of values.

I've come up with a small working example of the issue, and was wondering if anyone knows a good way to break ties/truly get the desired number of rows when using the dplyr function top_n. I was thinking I could use another ranking column to break ties, but looking at the top_n documentation here: https://www.rdocumentation.org/packages/dplyr/versions/0.7.8/topics/top_n, it seems like it only accepts one metric.

I've been bandaiding the issue by just sorting by this second metric, but I would really like to use my first because it generally gives much better results. Any help would be appreciated! Thank you in advance!

P.S. In python I believe the lambda function can handle this issue, but I am not as familiar with R.

Small example

library(dplyr)
df = data.frame(category = c(rep("red",4), rep("green",4), rep("blue",4)),
               metric1 = c(1,1,2,3,
                          1,2,2,3,
                          1,2,1,3),
               metric2 = c(rep(1:4,3)))
head(df)
  category metric1 metric2
1      red       1       1
2      red       1       2
3      red       2       3
4      red       3       4
5    green       1       1
6    green       2       2

df %>% 
    group_by(category) %>%
    top_n(2,wt=metric1)
# A tibble: 7 x 3
# Groups:   category [3]
  category metric1 metric2
  <chr>      <dbl>   <int>
1 red            2       3
2 red            3       4
3 green          2       2       <---- I'd like to keep only one!
4 green          2       3       <----
5 green          3       4
6 blue           2       2
7 blue           3       4
0 Answers
Related