Here is my data:
df <- tibble::tribble(
~group, ~sort_var, ~var, ~desired_rank,
1L, 3L, "A", 1L,
1L, 4L, "A", 1L,
1L, 5L, "D", 2L,
1L, 6L, "C", 3L,
2L, 1L, "D", 1L,
2L, 2L, "B", 2L,
2L, 3L, "C", 3L,
2L, 4L, "B", 2L)
The data is already arranged using sort_var by group. I want to rank the contents of the var as they come within the group. For example, D comes 2nd within group 1 so it gets rank 2, while it get's rank 1 in group 2 as it comes 1st in that group.
I tried this, but getting an incorrect output.
df %>% group_by(group) %>%
mutate(incorrect_rank = rank(var))
Please suggest a solution.