[R] Sequence of ordered variable to add as column

Duarte Viana viana.sptd at gmail.com
Fri Mar 19 11:25:12 CET 2010


Hello all,

As an example, consider the following dataframe

> df<-data.frame(id=c("b","b","a","a","a"),ord=c(2,1,1,3,2))
> dates<-as.Date(c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92"),"%m/%d/%y")
> df$dates<-dates

which was ordered with

> df<-df[order(df$id,df$dates),]

Now I would like to add a column containing a sequence (disregarding
ties) that represents the order of the variable
"dates" in each case of the variable "id", resulting in this dataframe:

> seq.id<-c(1,2,3,1,2)
> df$seq.id<-seq.id

  id ord      dates seq.id
3  a   1 1992-01-14      1
5  a   2 1992-02-01      2
4  a   3 1992-02-28      3
1  b   2 1992-02-27      1
2  b   1 1992-02-27      2


Thanks in advance,

Duarte Viana



More information about the R-help mailing list