[R] How to obtain the original indices of elements after sorting

Rolf Turner rolf.turner at xtra.co.nz
Mon Mar 11 02:41:22 CET 2013


?order

     cheers,

         Rolf Turner

On 03/11/2013 02:24 PM, Jie wrote:
> Dear All,
>
> Suppose I have a vector X = (x_1,  x_2, ....,  x_n), X_sort = sort(X)
> = (x_(1), x_(2), ... , x(n) ),
> and I would like to know the original position of these ordered x_(i)
> in X, how can I do it?
>
> case 1: all values are unique
> x <- c( 3, 5, 4, 6)
> x.sort <- sort(x) #
> # I would like to obtain a vector (1, 3, 2, 4) which indicates that 3
> in x is still the 1st element in x.sort, 5 is at the 3rd position in
> x.sort. etc.
>
> case 2: some x_i's have the same value
> x <- c(3, 3, 5, 5, 4, 4, 6, 6)
> I would like to obtain a vector as (1, 2, 5, 6, 3, 4, 7, 8)
>
> I do not want to use which and loop over the vector to do it since for
> a long vector it is not fast enough.
> Thank you for your suggestion.



More information about the R-help mailing list