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)
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With