2
$\begingroup$

Given a dataset like this:

ds = Dataset@{<|"C_1" -> 5, "C_2" -> 2, "C_3" -> 3|>, <|"C_1" -> 2, 
     "C_2" -> 3, "C_3" -> 4|>, <|"C_1" -> 3, "C_2" -> 2, 
     "C_3" -> 1|>, <|"C_1" -> 2, "C_2" -> 3, "C_3" -> 8|>};

Notice that there is _ in column names occasionally. I want to define a function to sort rows with columns set up dynamically to be used like this: fDatasetSortBy["C_1","C_3","C_2"] or fDatasetSortBy["C_2","C_3","C_1"].

(*1st*) fDatasetSortBy[s1_, s2_, s3_] := ds[SortBy[{# s1,# s2, # s3}&]]

or

(*2nd*) fDatasetSortBy[s1_, s2_, s3_] := 
  ds[SortBy[ToExpression["{#" <> s1 <> ",#" <> s2 <> ", #" <> s3 <> "}&"]]]

but the 1st case does not work, the 2nd one comes up Failure[...] ("MessageTemplate" :> Function::slota) if there _ exists in column names. How to make a pefect one? Thanks!

$\endgroup$
3
$\begingroup$
ClearAll[fDatasetSortBy]
fDatasetSortBy[s1_, s2_, s3_] := ds[SortBy[{#[s1] &, #[s2] &, #[s3] &}]]

Examples:

fDatasetSortBy["C_1", "C_3", "C_2"]

enter image description here

fDatasetSortBy["C_2", "C_3", "C_1"]

enter image description here

Note: you can also use ds[SortBy[{Slot[s1] &, Slot[s2] &, Slot[s3] &}]].

$\endgroup$
  • $\begingroup$ haha...well done, thanks! $\endgroup$ – Jerry Jan 17 at 11:18

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.