How to create a counter/numeration by group?

aggregate, r

Solution

First, check that your date really is in a date format (not a `factor`) using `class(your_dataset$date)`. IF not, use `ymd` from `lubridate` to convert it.

Second, use `rank` to get the rank. (Easier than you think, right!)

your_dataset$rank <- rank(your_dataset$date)

There are a few different methods for breaking ties that you might want to explore.

Upon rereading your question, I see you don't want to rank the dates, you want a counter within the dates. To do this, first check that your dataset is ordered by date.

o <- with(your_dataset, order(date))
your_dataset <- your_dataset[o, ]

Then call `seq_len` on each chunk of date.

counts <- as.numeric(table(your_dataset$date))
your_dataset$rank <- unlist(lapply(counts, seq_len))

Problem

I've got some data in the following shape: UPDATE: My data has an extra variable I'd like to group by. I used ddply with the below solution provided by Richie but did not work. ``` Country,group, date US,A,'2011-10-01' US,B,'2011-10-01' US,C,'2011-10-01' MX,D,'2011-10-01' UK,E,'2011-10-02' UK,B,'2011-10-02' UK,A,'2011-10-02' UK,C,'2011-10-02' ``` The data frame is already ordered so A came first, B second and so on so forth. What I am trying to create is a rank variable by date like this: ``` Country,group, date,rank US,A,'2011-10-01',1 US,B,'2011-10-01',2 US,C,'2011-10-01',3 MX,D,'2011-10-01',1 UK,E,'2011-10-02',1 UK,B,'2011-10-02',2 UK,A,'2011-10-02',3 UK,C,'2011-10-02',4 .... ```

Original source

Related problems