10
$\begingroup$

I am trying to find the minimum values for all elements in a list of associations, below is an example

x = {<|"a"-> 4, "b"->9, "c"->15|>, <|"a"->21, "b"->11, "c"->1|>, <|"a"->12, "b"->3, "c"->21|>}

Required output for Min {<|"a"-> 2, "b"->3, "c"->1|>}

Required output for Max {<|"a"-> 21, "b"->11, "c"->15|>}

My attempt for Max: MaximalBy[Values]@x Result: {<|"a" -> 21, "b" -> 11, "c" -> 1|>}

for Min: MinimalBy[Values]@x Result: {<|"a" -> 4, "b" -> 9, "c" -> 15|>}

Is there an elegant way to achieve this result?

$\endgroup$
  • 1
    $\begingroup$ I don't get it. How is the key a getting the value 2? That value does not appear for a in any of the associations. Similarly, why is the value of c not equal to 21 in the maximal result? $\endgroup$ – Shredderroy Dec 7 '18 at 6:30
13
$\begingroup$

How about

a = {
    <|"a" -> 4, "b" -> 9, "c" -> 15|>,
    <|"a" -> 21, "b" -> 11, "c" -> 1|>,
    <|"a" -> 12, "b" -> 3, "c" -> 21|>
};

Merge[a, Min]

(*<|"a" -> 4, "b" -> 3, "c" -> 1|>*)

Merge[a, Max]

(*<|"a" -> 21, "b" -> 11, "c" -> 21|>*)

EDIT

Improved, as per Kuba's suggestion.

$\endgroup$
6
$\begingroup$
Random`Private`MapThreadMin[x]
Random`Private`MapThreadMax[x]

<|"a" -> 4, "b" -> 3, "c" -> 1|>

<|"a" -> 21, "b" -> 11, "c" -> 21|>

$\endgroup$
  • 1
    $\begingroup$ is there any list out there for these "hidden" commands? Or do you happen to have a favourite list that you can share with us? $\endgroup$ – Soner Dec 7 '18 at 12:33
  • 1
    $\begingroup$ A good try is always ?**` ;) Honestly, I learned this trick very recently from Carl Woll. Some other good place to look for such things is What are some useful undocumented Mathematica functions? $\endgroup$ – Henrik Schumacher Dec 7 '18 at 13:45
  • $\begingroup$ Thanks, I am checking the link right now :) $\endgroup$ – Soner Dec 7 '18 at 21:35
1
$\begingroup$

You may use Query and MinMax.

With x as in OP.

Query[Transpose /* Map[MinMax]]@x
<|"a" -> {4, 21}, "b" -> {3, 11}, "c" -> {1, 21}|>

You can produce a more descriptive result with AssociationThread.

res = Query[Transpose /* Map[AssociationThread[{"Min", "Max"}, MinMax@#] &]]@x
<|"a" -> <|"Min" -> 4, "Max" -> 21|>, 
  "b" -> <|"Min" -> 3, "Max" -> 11|>, 
  "c" -> <|"Min" -> 1, "Max" -> 21|>|>

Which you can then access by Key with Association's syntax sugar.

res["a", "Max"]
21

Hope this helps.

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