[R] inverse function of order()

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Oct 4 18:09:37 CEST 2004


Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:

> Wolfram Fischer wrote:
> > I have:
> >  d <- sample(10:100, 9)
> >  o <- order(d)
> >  r <- d[o]
> > How I can get d (in the original order), knowing only r and o?
> >
> 
>   r[order(o)]?
> 
>   > d=sample(10:100,9)
>   > o=order(d)
>   > r=d[o]
>   > all(r[order(o)] == d)
>   [1] TRUE
> 
>   tested and works for duplicates in d as well.

Neat. It is O(n log n) though. 

 D <- numeric(length(r))
 D[o] <- r

should be O(n)

Notice btw that 

> rank(d)
[1] 3 4 1 8 5 6 9 7 2
> order(order(d))
[1] 3 4 1 8 5 6 9 7 2


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list