7
$\begingroup$

I have the following two lists:

ids = {5, 11, 17, 24, 31, 37, 40, 39, 38, 33, 32, 25}

values = {0.0351563, 0.131836, 0.086792, 0.0637894, 0.065752, 0.191388, 0.063796, 0.173784, 0.0503769, 0.0875244, 0.0146484, 0.0351563}

where entries in values correspond to entries in ids.

I now wish to sort ids in ascending order while maintaining the correspondence to values, such that elements in values must be changed according to the changes made to ids.

How can that be achieved?

$\endgroup$
1
  • $\begingroup$ values[[Ordering@ids]] and SortBy[Transpose[{ids, values}], First] == Transpose[{Sort@ids, values[[Ordering@ids]]}] $\endgroup$
    – user1066
    Dec 2, 2018 at 17:53

4 Answers 4

8
$\begingroup$
With[{p = Ordering[ids]},
 idsnew = ids[[p]];
 valuesnew = values[[p]];
 ]
idsnew
valuesnew

{5, 11, 17, 24, 25, 31, 32, 33, 37, 38, 39, 40}

{0.0351563, 0.131836, 0.086792, 0.0637894, 0.0351563, 0.065752, 0.0146484, 0.0875244, 0.191388, 0.0503769, 0.173784, 0.063796}

$\endgroup$
2
  • $\begingroup$ This generates an error for me: Set::write: Tag Times in valuesnew {5,11,17,24,25,31,32,33,37,38,39,40} is Protected. $\endgroup$
    – user120911
    Dec 2, 2018 at 16:59
  • $\begingroup$ Sorry, I missed a semicolon that was necessary after wrapping everything with With. Please try again. $\endgroup$ Dec 2, 2018 at 17:07
6
$\begingroup$

I would keep them together while sorting.

SortBy[Transpose[{ids, values}], First]
{{5, 0.0351563}, {11, 0.131836}, {17, 0.086792}, {24, 0.0637894}, {25,
   0.0351563}, {31, 0.065752}, {32, 0.0146484}, {33, 0.0875244}, {37, 
  0.191388}, {38, 0.0503769}, {39, 0.173784}, {40, 0.063796}}
$\endgroup$
1
5
$\begingroup$
AssociationThread[ids, values] // KeySort

Edit To extract keys and values

sorted = AssociationThread[ids, values] // KeySort
sortedIds = Keys[sorted]
sortedValues = Values[sorted]
$\endgroup$
2
  • $\begingroup$ This looks simple, but how do I work with these afterwards? $\endgroup$
    – user120911
    Dec 2, 2018 at 17:00
  • $\begingroup$ @user120911 Added sorted key / value extraction. $\endgroup$ Dec 2, 2018 at 17:24
3
$\begingroup$

Since Sort sort it by the first entry by default

Sort@Transpose@{ids, values}

{{5, 0.0351563}, {11, 0.131836}, {17, 0.086792}, {24, 0.0637894}, {25, 0.0351563}, {31, 0.065752}, {32, 0.0146484}, {33, 0.0875244}, {37, 0.191388}, {38, 0.0503769}, {39, 0.173784}, {40, 0.063796}}

$\endgroup$
1
  • 3
    $\begingroup$ A problem that arises here with Transpose is is that it unpacks arrays: ids is a list of integers and values is a list of machine reals. So both can be packed separately; but not Transpose@{ids, values} as it has mixed data types. This may become important when processing large datasets. $\endgroup$ Dec 2, 2018 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.