0

I try to build the ranks according to groups based on the values of two variables in R.

Data example:

A   B    group   rank
9   2     C      3
12  9     C      2
12  10    C      1
8   5     C      4
8   5     C      4

10   3    D      5
15  10    D      1
14  12    D      2
14   8    D      3
14   8    D      3

I know how to use group_by and rank; however, if I wanna use frank and by = group; it does not work.

Thank you very much!

Aleya
  • 71
  • 4

1 Answers1

0

While it's not quite clear how would you define ranking with multiple columns, you'd get a desired result with something like this:

library(dplyr)
df <- read.table(header = TRUE, text = 
"A   B    group   rank_ref
9   2     C      3
12  9     C      2
12  10    C      1
8   5     C      4
8   5     C      4

10   3    D      5
15  10    D      1
14  12    D      2
14   8    D      3
14   8    D      3")

# use A*10 to prioritize A over B
df %>% 
  group_by(group) %>% 
  mutate(rank_new = min_rank(desc(A*10+B))) %>% 
  ungroup()
#> # A tibble: 10 × 5
#>        A     B group rank_ref rank_new
#>    <int> <int> <chr>    <int>    <int>
#>  1     9     2 C            3        3
#>  2    12     9 C            2        2
#>  3    12    10 C            1        1
#>  4     8     5 C            4        4
#>  5     8     5 C            4        4
#>  6    10     3 D            5        5
#>  7    15    10 D            1        1
#>  8    14    12 D            2        2
#>  9    14     8 D            3        3
#> 10    14     8 D            3        3

Created on 2023-08-29 with reprex v2.0.2

margusl
  • 7,804
  • 2
  • 16
  • 20