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

Pascal Oettli kridox at ymail.com
Mon Mar 11 02:43:09 CET 2013


Hi,

The answer to your question is written on the help page.

?sort

HTH,
Pascal


On 11/03/13 10:24, 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.
>
> Best wishes,
> Jie
>
> ______________________________________________
> 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