0

I want to rank each id based on two categories: cat1 and cat2. For example, "death" < "pd" < "pr", and 1 < 2 < 3 < 4, and thus, the rank for each patient should be as follows:

id  cat1    cat2    rank
1   death   1        1
2   death   2        2
3   death   3        3
4   death   4        4
5   pd      1        5
6   pd      2        6
7   pd      3        7
8   pd      4        8
9   pr      1        9
10  pr      2        10
11  pr      3        11
12  pr      4        12

Sophia
  • 377
  • 1
  • 12

1 Answers1

0

We may need to arrange (in case it is not ordered) and then use row_number()

library(dplyr)
df %>% 
    arrange(match(cat1, c('death', 'pd', 'pr')), cat2) %>%
    mutate(rnk2 = row_number())

-output

id  cat1 cat2 rank rnk2
1   1 death    1    1    1
2   2 death    2    2    2
3   3 death    3    3    3
4   4 death    4    4    4
5   5    pd    1    5    5
6   6    pd    2    6    6
7   7    pd    3    7    7
8   8    pd    4    8    8
9   9    pr    1    9    9
10 10    pr    2   10   10
11 11    pr    3   11   11
12 12    pr    4   12   12

data

df <- structure(list(id = 1:12, cat1 = c("death", "death", "death", 
"death", "pd", "pd", "pd", "pd", "pr", "pr", "pr", "pr"), cat2 = c(1L, 
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), rank = 1:12),
 class = "data.frame", row.names = c(NA, 
-12L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks for your solution. However, there could be ties, e.g., id 1 and 2 can belong to the same "Death" category with "rank" 1, and thus, for rnk2, they should have the same rank. Thank you. – Sophia Aug 27 '21 at 13:02
  • @sophia can you update your post with a new example and expected output. thanks – akrun Aug 27 '21 at 19:56