2
$\begingroup$

I would like to TakeLargestBy a nested variable in a Dataset. To be clearer, here is code to make an example dataset

nObs = 4;
mkPartAssoc = 
  Association[
    Thread[Rule[{"part1", "part2", "part3"}, 
      RandomInteger[{4, 9}, 3]]]] &;
data = Dataset@
  MapThread[
   Association, {Thread[Rule["ID", Range@nObs]], 
    Thread[Rule["thing", 
      Reap[Do[Sow[mkPartAssoc[]], nObs]][[2, 1]]]]}]

Sample result

enter image description here

I can take the largest 1 observation by the non-nested variable as follows: data[TakeLargestBy["ID", 1]],

But how can I take the largest 1 observation by "part1"? My attempts below do not work: data[TakeLargestBy["ID"["part1"], 1]]

data[TakeLargestBy["part1", 1]]

$\endgroup$
6
$\begingroup$

One way is to use a pure function that extracts the desired subvalue from each association:

data[TakeLargestBy[#["thing", "part1"] &, 1]]

dataset screenshot

Part syntax could be used instead:

data[TakeLargestBy[#[["thing", "part1"]] &, 1]]

For nested associations as in the question, this is equivalent to the extraction syntax above. But it is more general in that it can be used to index into hierarchies whose levels are arbitrary mixtures of associations and lists.

The desired subparts could also by accessed by means of a subquery:

data[TakeLargestBy[Query["thing", "part1"], 1]]
$\endgroup$

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.