0

I have these set of variables in the column Num I want to create another column that ranks them with size similar to rankt below but I don't like how this is done.

 x <- data.frame("Num" = c(2,5,2,7,7,7,2,5,5))

x$rankt <- rank(x$Num)

  Num rankt
1   2     2
2   5     5
3   2     2
4   7     8
5   7     8
6   7     8
7   2     2
8   5     5
9   5     5

Desired Outcome I would like for rankt

  Num rankt
1   2     1
2   5     2
3   2     1
4   7     3
5   7     3
6   7     3
7   2     1
8   5     2
9   5     2
FalconX
  • 53
  • 7

2 Answers2

2

Well, a crude approach is to turn them to factors, which are just increasing numbers with labels, and then fetch those numbers:


x <- data.frame("Num" = c(2,5,2,7,7,7,2,5,5))
x$rankt <- as.numeric(as.factor( rank(x$Num) ))
x

It produces:

  Num rankt
1   2     1
2   5     2
3   2     1
4   7     3
5   7     3
6   7     3
7   2     1
8   5     2
9   5     2
Sirius
  • 5,224
  • 2
  • 14
  • 21
1

A solution with dplyr

library(dplyr)
x1 <- x %>% 
  mutate(rankt=dense_rank(desc(-Num)))

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66