-1

I have a data set that is organized like this

Date:
4/2/2018
5/6/2018
4/2/2018
7/1/2018
7/1/2018
5/6/2018

I would like it to be organized like this:

Date:                ID:
4/2/2018             1 
5/6/2018             2
4/2/2018             1
7/1/2018             3
7/1/2018             3
5/6/2018             2

Does anyone know how to do this? My data is organized in a data table with date as one of the columns and I need to create a new column called id.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49

1 Answers1

0

We can use rleid from data.table:

library(data.table)
dt[order(Date),ID:=rleid(Date)]

Result:

       Date ID
1: 4/2/2018  1
2: 5/6/2018  2
3: 4/2/2018  1
4: 7/1/2018  3
5: 7/1/2018  3
6: 5/6/2018  2

Data:

dt <- read.table(text = "Date
4/2/2018
                 5/6/2018
                 4/2/2018
                 7/1/2018
                 7/1/2018
                 5/6/2018", header = TRUE, stringsAsFactors = FALSE)

setDT(dt)
acylam
  • 18,231
  • 5
  • 36
  • 45