[R] Odp: Sequence of ordered variable to add as column
Petr PIKAL
petr.pikal at precheza.cz
Fri Mar 19 11:46:18 CET 2010
Hi
r-help-bounces at r-project.org napsal dne 19.03.2010 11:25:12:
> 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
Here is one option but I believe others will come with more clever one.
df$seq.id<-unlist(tapply(as.numeric(df$id), df$id, order))
Regards
Petr
>
>
> Thanks in advance,
>
> Duarte Viana
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list