I would like to use row_numbers to output a ranking variable in which the row ranked 1 has the highest vote count, and descending:
df<-tibble(x=letters[1:4], votes=c(30,55,21,12))
If I use row_number I have this output
af%>%mutate(rank=row_number(votes))
# A tibble: 4 x 3
x votes rank
<chr> <dbl> <int>
1 a 30 3
2 b 55 4
3 c 21 2
4 d 12 1
But my desired output for rank would be 2,1,3,4
Thanks very much.
We could use the rank()
function with a -
before votes
indicating the descending order:
library(dplyr)
df %>%
mutate(rank = rank(-votes))
x votes rank
<chr> <dbl> <dbl>
1 a 30 2
2 b 55 1
3 c 21 3
4 d 12 4