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

PIKAL Petr petr.pikal at precheza.cz
Mon Mar 11 08:10:53 CET 2013


Hi

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Jie
> Sent: Monday, March 11, 2013 2:24 AM
> To: r-help
> Subject: [R] How to obtain the original indices of elements after
> sorting
> 
> 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) #

That is why order is included.

> x <- c( 3, 5, 4, 6)
> order(x)
[1] 1 3 2 4
>

I believe that it is mentioned in sort help page.

Regards
Petr

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