1
$\begingroup$

A $\mathtt{Dataset}$ has a column $C$ with enumerated values $c_i$, to each of which a number $n_{c_i}$ is manually assigned. The $\mathtt{Dataset}$ needs to be sorted based on the numbers.


MWE: Suggest there's a $\mathtt{Dataset}$:

ds = Dataset[
  AssociationThread[{"ID", "Food"}, 
     StringSplit[#, ","]] & /@ {"1,Apple", "2,Banana", "3,Banana", 
    "4,Cherry", "5,Apple"}]

The column "Food" of any record will be one of "Apple", "Banana", and "Cherry".

Now, for some reason, One’d like to sort the records by Column "Food", assigning 2 to "Apple", 1 to "Banana", and 3 to "Cherry" (maybe 0 to anything else). The result $\mathtt{Dataset}$ will thus have Column "ID" as $\mathtt{\{2, 3, 1, 5, 4\}}$:

expectedDs = 
 Dataset[AssociationThread[{"ID", "Food"}, 
     StringSplit[#, ","]] & /@ {"1,Apple", "2,Banana", "3,Banana", 
     "4,Cherry", "5,Apple"}[[{2, 3, 1, 5, 4}]]]
$\endgroup$
1
  • 1
    $\begingroup$ f[“Apple”] = 2; f[“Banana”] = 1; f[“Cherry”] = 3; dat[SortBy[Key[“Food”] /* f]] $\endgroup$ Feb 19, 2021 at 6:42

1 Answer 1

1
$\begingroup$
ClearAll[sort]
sort = AssociationThread[{"Apple", "Banana", "Cherry"}, {2, 1, 3}]; 

ds[SortBy[sort @ #Food &]]

enter image description here

$\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.