Add order of records according to date and id

Asked

Viewed 61 times

2

In R, I have the following data:

 id      date        
2380    10/30/12    
2380    10/31/12    
2380    11/1/12     
2380    11/2/12     
20103   10/30/12   
20103   12/31/12

And I want to add a column with the order of the records according to date and id, for example:

id      date       ordem 
2380    10/30/12    1
2380    10/31/12    2
2380    11/1/12     3
2380    11/2/12     4
20103   10/30/12    1
20103   12/31/12    2
20100   10/05/12    2
20100   05/04/12    1
20100   11/1/12     3

1 answer

4


In R base, you can do what the question asks with the function ave. It should be noted that the output of ave is of the same class as the first argument, so you must pass the column date as a numerical vector.

dados$date <- as.Date(dados$date, "%m/%d/%y")
dados$ordem2 <- ave(as.numeric(dados$date), dados$id, FUN = order)

dados
#     id       date ordem ordem2
#1  2380 2012-10-30     1      1
#2  2380 2012-10-31     2      2
#3  2380 2012-11-01     3      3
#4  2380 2012-11-02     4      4
#5 20103 2012-10-30     1      1
#6 20103 2012-12-31     2      2
#7 20100 2012-10-05     2      2
#8 20100 2012-05-04     1      1
#9 20100 2012-11-01     3      3

Dice.

dados <- read.table(text = "
id      date       ordem 
2380    10/30/12    1
2380    10/31/12    2
2380    11/1/12     3
2380    11/2/12     4
20103   10/30/12    1
20103   12/31/12    2
20100   10/05/12    2
20100   05/04/12    1
20100   11/1/12     3
", header = TRUE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.