0
$\begingroup$

I had looked at previous answers for this but was unable to find a solution. I have the following code:

dnames1={"A1","A2","A3","A4","A5","A6"}
dnumber={20,20,11,21,19,20}

newdnumber=TakeSmallest[dnumber,6]


AssociationThread[dnames,dnumber]

The positions of the strings given in "dnames1" correspond to the values in the same position given by list "dnumber" (this can be seen through the AssociationThread). I then rearranged the list "dnumber" to go from the smallest number to the largest, giving a new list designated "newdnumber." I'm trying to then produce a new corresponding list called "newdnames1" which reflects the new ordering given by "newdnumber." This would give an output of:

newdnames1={"A3","A5","A1","A2","A6","A4"}

I've tried the following to solve this question:

assoc=AssociationThread[dnumber,dnames1]
newdnumber/.assoc

but the main issue is that the AssociationThreaddoes not associate the correct list of strings if there are repeating values given in dnumber (I.e. The number 20 appears 3 times but the association only ever assigns "A6"`a value of 20 and it never assigns strings "A1" or "A2". Any help producing newdnames1 would be greatly appreciated.

$\endgroup$
2
  • 1
    $\begingroup$ why not just dnames1[[Ordering[dnumber]]] to get newdnames1 directly? $\endgroup$
    – kglr
    Commented Jun 10, 2020 at 22:59
  • 1
    $\begingroup$ If you insist on using associations, you could use Keys@Sort@AssociationThread[dnames1, dnumber] $\endgroup$
    – MarcoB
    Commented Jun 10, 2020 at 23:55

1 Answer 1

1
$\begingroup$

You can get newdnames1 directly using

dnames1[[Ordering[dnumber]]]

If you you want to work with associations, for newdnumber, you can get the desired result simply using Sort:

assoc1 = AssociationThread[dnames1, dnumber]
<|"A1" -> 20, "A2" -> 20, "A3" -> 11, "A4" -> 21, "A5" -> 19,   "A6" -> 20|>
assoc2b = Sort[assoc1]
 <|"A3" -> 11, "A5" -> 19, "A1" -> 20, "A2" -> 20, "A6" -> 20,  "A4" -> 21|>
Keys @ assoc2
 {"A3", "A5", "A1", "A2", "A6", "A4"}

For general newdnumber, you can sort assoc1 using SortBy[PositionIndex[newdnumber]]:

assoc2 = SortBy[PositionIndex[newdnumber]]@assoc1
<|"A3" -> 11, "A5" -> 19, "A4" -> 21, "A1" -> 20, "A2" -> 20,  "A6" -> 20|>
Keys @ assoc2
 {"A3", "A5", "A1", "A2", "A6", "A4"}
SeedRandom[1]

shuffledDnumber = RandomSample[dnumber]
 {19, 11, 20, 20, 21, 20}
assoc3 = SortBy[PositionIndex[shuffledDnumber]]@assoc1
<|"A5" -> 19, "A3" -> 11, "A4" -> 21, "A1" -> 20, "A2" -> 20,  "A6" -> 20|>
Keys @ assoc3
{"A5", "A3", "A4", "A1", "A2", "A6"}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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