IAMTubby
IAMTubby

Reputation: 1687

how to get index of sorted array elements

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)

Upvotes: 35

Views: 47190

Answers (3)

shen Eric
shen Eric

Reputation: 21

if you want get the same array indices returned by which, you should use arrayInd function:

array = matrix(rnorm(36),nrow=6)
sortIndex = sort(array, index.return=TRUE)$ix
array_indices = arrayInd(sortIndex,dim(array),dimnames(array),useNames = TRUE)

Upvotes: 0

akrun
akrun

Reputation: 887951

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

Upvotes: 28

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

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

Upvotes: 50

Related Questions