[R] Number of replications of a term

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Jan 24 18:32:25 CET 2006


Laetitia Marisa <Laetitia.Marisa at cgm.cnrs-gif.fr> writes:

> Hello,
> 
> Is there a simple and fast function that returns a vector of the number 
> of replications for each object of a vector ?
> For example :
> I have a vector of IDs :
> ids <- c( "ID1", "ID2", "ID2", "ID3", "ID3","ID3", "ID5")
> 
>  I want the function returns the following vector where each term is the 
> number of replicates for the given id :
> c( 1, 2, 2, 3,3,3,1 )
> 
> Of course I have a vector of more than 40 000 ID and the function I 
> wrote (it orders my data and checks on ID:Name of the data if the next 
> term is the same as the previous one (see below) ) is really slow 
> (30minutes for 44290 terms). But I don't have time by now to write a C 
> function.
> Thanks a lot for your help,

Will this do it?

> table(ids)[ids]
ids
ID1 ID2 ID2 ID3 ID3 ID3 ID5
  1   2   2   3   3   3   1

Or (could be faster):

> f <- factor(ids,levels=unique(ids))
> as.vector(table(f))[f]
[1] 1 2 2 3 3 3 1


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list