4
$\begingroup$

I have a datatset , and I want to sort the elements in the second column so that the elements in the other columns change accordingly.

dataset= {<|index -> 1, name -> N, x-> 1, y -> 1.5, z -> 1.7|>, 
          <|index -> 2, name -> C, x-> 2, z -> 2.7|>, 
          <|index -> 3, name -> H, x-> 3, y -> 3.5, z -> 3.7|>,...}

e.g. i want change name element to HCN instead of NCH. when i use dataset[All, "name"] = HCN just elements in name column were changed but their values in rest XYZ column did not change.

$\endgroup$
1
  • 1
    $\begingroup$ dataset[[{3,2,1}]]? It doesn't look like there's a natural sort to be taken advantage of there, but you can just re-pick the dataset manually (with Part ([[...]])) since there's only 3 members. $\endgroup$
    – eyorble
    Commented Jun 2, 2020 at 19:16

1 Answer 1

2
$\begingroup$
myordering = AssociationThread[{H, C, N}, Range[3]];

SortBy[myordering @ #[name] &] @ dataset
 {<|index -> 3, name -> H, x -> 3, y -> 3.5, z -> 3.7|>, 
  <|index -> 2, name -> C, x -> 2, z -> 2.7|>, 
  <|index -> 1, name -> N, x -> 1, y -> 1.5, z -> 1.7|>}
SeedRandom[777]
dataset2 = RandomChoice[dataset, 15];

Row[Column /@ {dataset2, SortBy[myordering @ #[name]&] @ dataset2}, 
 Spacer[10]]

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.