Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get index of sorted array elements

Tags:

r

Say I have an array in R : c(10, 7, 4, 3, 8, 2) Upon sorting, this would be : c(2, 3, 4, 7, 8, 10)

What is the best way in R to return the indices for the sorted array elements from the original array. I'm looking for an output like : 6(index of 2), 4(index of 3), 3(index of 4), 2(index of 7), 5(index of 8), 1(index of 10)

like image 302
IAMTubby Avatar asked Nov 25 '14 07:11

IAMTubby


People also ask

How do I return an index to a sorted list in Python?

You can use the python sorting functions' key parameter to sort the index array instead. perhaps key=s. __getitem__ ? In case you also want the sorted array, sorted_s = [s[k] for k in ind_s_to_sort] , where ind_s_to_sort is the index acquired from this method.

How do you find the index number of an element?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


2 Answers

The function you're looking for is order:

> x [1] 10  7  4  3  8  2 > order(x) [1] 6 4 3 2 5 1 
like image 58
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 21 '22 04:09

A5C1D2H2I1M1N2O1R2T1


sort has index.return argument, which by default is FALSE

x <- c(10,7,4,3,8,2) sort(x, index.return=TRUE) #returns a list with `sorted values`  #and `$ix` as index. #$x #[1]  2  3  4  7  8 10  #$ix #[1] 6 4 3 2 5 1 

You can extract the index by

sort(x, index.return=TRUE)$ix #[1] 6 4 3 2 5 1 
like image 21
akrun Avatar answered Sep 24 '22 04:09

akrun