2

I have following dataframe in R

 ID    Date     
 1     01-01-2018
 2     02-01-2018
 3     03-01-2018
 4     03-01-2018
 5     03-01-2018
 6     04-01-2018
 7     04-01-2018

My desired dataframe is

 ID    Date          Rank
 1     01-01-2018     1
 2     02-01-2018     2
 3     03-01-2018     3
 4     03-01-2018     3
 5     03-01-2018     3
 6     04-01-2018     4
 7     04-01-2018     4

Rank should change when it encounters unique dates otherwise rank should be same.How can I do it in R ?

Neil
  • 7,937
  • 22
  • 87
  • 145
  • https://stackoverflow.com/questions/24119599/how-to-assign-a-unique-id-number-to-each-group-of-identical-values-in-a-column – user20650 Apr 25 '18 at 09:43

2 Answers2

4

It can be done with match from base R

df1$Rank <- with(df1, match(Date, unique(Date)))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

The data.table package offers frank (fast rank) which is much faster than rank. frank also offers an additional ties.method called "dense", which is exactly what you need.

library(data.table)
A <- data.table("ID" = c(1,2,3,4,5,6,7),
                "Date" = c("01-01-2018",
                           "02-01-2018",
                           "03-01-2018",
                           "03-01-2018",
                           "03-01-2018",
                           "04-01-2018",
                           "04-01-2018"))

A[, rank := frank(Date, ties.method ="dense")]

> A
   ID       Date rank
1:  1 01-01-2018    1
2:  2 02-01-2018    2
3:  3 03-01-2018    3
4:  4 03-01-2018    3
5:  5 03-01-2018    3
6:  6 04-01-2018    4
7:  7 04-01-2018    4

You can also use the build it .GRP (group count) function in combination with "by":

A[, rank := .GRP, by = Date]

The result is exactly the same as above.