0

First of all: Sorry if this question might sound stupid...or I have formatted it incorrectly, I'm new to this. I have the following data:

  Value       Date IDnum
1   230 2010-02-01     1
2   254 2011-07-07     2
3   300 2011-12-14     1
4   700 2011-01-23     3
5   150 2010-08-31     3
6   100 2010-05-06     1

Created using the following code:

Value <- c(230, 254, 300, 700, 150, 100)  
Date <- as.Date(c("01/02/2010", "07/07/2011", "14/12/2011", "23/01/2011", "31/08/2010", "06/05/2010")
            , "%d/%m/%Y")
IDnum <- c(001, 002, 001, 003, 003, 001)  
MyData <- data.frame(Value, Date, IDnum)

I need R to create a column which counts and enumerates every row according to whether its the first, second etc observation for the given IDnum, by date. Thus giving me something similar:

  Value       Date IDnum Obs
1   230 2010-02-01     1   1
2   254 2011-07-07     2   1
3   300 2011-12-14     1   3
4   700 2011-01-23     3   2
5   150 2010-08-31     3   1
6   100 2010-05-06     1   2

Thanks

1 Answers1

-1
library(data.table)
df$Date <- as.Date(df$Date, format = "%Y-%m-%d")
setDT(df)[, Obs := order(Date),by = .(IDnum)]

library(dplyr)
df %>% group_by(IDnum) %>% mutate(Obs = order(Date))

#   Value       Date IDnum Obs
#1:   230 2010-02-01     1   1
#2:   254 2011-07-07     2   1
#3:   300 2011-12-14     1   3
#4:   700 2011-01-23     3   2
#5:   150 2010-08-31     3   1
#6:   100 2010-05-06     1   2
joel.wilson
  • 8,243
  • 5
  • 28
  • 48
  • to the person who downvoted, i don't think you downvoted because It was a duplicate answer, because you yourselves answer duplicate questions daily! – joel.wilson Jan 31 '17 at 09:31