5
votes

I have to arrays, one contain weights, and the other contain the categories (e.g w=[3, 4, 1, 2],x= ["a","b","c","c"]). Now, I'd like to sort the array x using the array of weights. How can one do this with the least amount of code? Is there a way of sorting an array and obtaining the corresponding indexes, so you can use this new sorted order in any other array with the same size?

I know that one can do this using DataFrames, but I'm looking for a way of doing this without resorting to that.

1

1 Answers

6
votes

You want the sortperm function.

w = [30, 40, 10, 20]
x = ["a","b","c","d"]
julia> permvec = sortperm(w)
4-element Array{Int64,1}:
 3
 4
 1
 2

julia> wsorted = w[permvec]
4-element Vector{Int64}:
 10
 20
 30
 40

julia> xsorted = x[permvec]
4-element Array{String,1}:
 "c"
 "d"
 "a"
 "b"