bzzbzzRzzbzz
bzzbzzRzzbzz

Reputation: 111

create unique id based on date in R

Am trying to figure out this..

I have this data set:

  id       date
1  1 2016-01-01
2  1 2016-01-01
3  1 2016-01-02 
4  2 2016-01-01
5  2 2016-01-03
6  2 2016-01-04
7  3 2016-01-01
8  3 2016-01-05
9  3 2016-01-05

so I am trying to use dplyr for this, by:

transformed <- data %>% group_by(id) %>% transform(., flag=match(date, unique(date)))

and i got this:

  id       date flag
1  1 2016-01-01    1
2  1 2016-01-01    1
3  1 2016-01-02    2
4  2 2016-01-01    1
5  2 2016-01-03    3
6  2 2016-01-04    4
7  3 2016-01-01    1
8  3 2016-01-05    5
9  3 2016-01-05    5 

but I am aiming for this,

  id       date flag
1  1 2016-01-01    1
2  1 2016-01-01    1
3  1 2016-01-02    2
4  2 2016-01-01    1
5  2 2016-01-03    2
6  2 2016-01-04    3
7  3 2016-01-01    1
8  3 2016-01-05    2
9  3 2016-01-05    2

from the first look, it does not seem that transform recognizes the piping command. The ids follow the date sequence though.

How do I achieve this using dplyr? For dates that are as.character or as.Date, it does not work.

Upvotes: 0

Views: 2492

Answers (2)

akrun
akrun

Reputation: 886938

We can use data.table

library(data.table)
setDT(df1)[, flag := match(date, unique(date)), by = id]

Upvotes: 1

LyzandeR
LyzandeR

Reputation: 37879

You could use the following for this:

library(dplyr)
df %>% 
 group_by(id) %>%
 #convert the date into a factor and then into numeric
 #which will give you what you need
 mutate(flag = as.numeric(as.factor(date)))

Output:

Source: local data frame [9 x 3]
Groups: id [3]

     id       date  flag
  <int>      <chr> <dbl>
1     1 2016-01-01     1
2     1 2016-01-01     1
3     1 2016-01-02     2
4     2 2016-01-01     1
5     2 2016-01-03     2
6     2 2016-01-04     3
7     3 2016-01-01     1
8     3 2016-01-05     2
9     3 2016-01-05     2

Upvotes: 2

Related Questions