[R] Ordering numbers

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Dec 2 21:52:06 CET 2009


Greg Snow wrote:
> Here is one way:
> 
>> id <- c(1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 1, 2, 2, 2, 3, 3, 1, 1, 1, 2, 3, 4,
> + 4, 4, 5, 5)
>> id
>  [1] 1 1 2 2 2 3 4 4 4 4 1 2 2 2 3 3 1 1 1 2 3 4 4 4 5 5
>> tmp <- rle(id)
>> tmp
> Run Length Encoding
>   lengths: int [1:12] 2 3 1 4 1 3 2 3 1 1 ...
>   values : num [1:12] 1 2 3 4 1 2 3 1 2 3 ...
>> rep( seq_along(tmp$lengths), tmp$lengths )
>  [1]  1  1  2  2  2  3  4  4  4  4  5  6  6  6  7  7  8  8  8  9 10 11 11 11 12
> [26] 12
> 

Here's another:


 > d <- diff(c(0,id))
 > d[d<0] <- 1
 > cumsum(d)
  [1]  1  1  2  2  2  3  4  4  4  4  5  6  6  6  7  7  8  8  8  9 10 11 
11 11 12
[26] 12

-- 
    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