I have the following Association
:
as = <|{5, 2, 1} -> 3, {6, 1, 4} -> 9, {5, 1, 9} -> 12, {5, 2, 4} -> 6, {6, 2, 8} -> 10|>;
I want to total the values on the right side of the rules according to the middle values of the keys to get
<|2 -> 19, 1 -> 21|>
The only way I know how to do this is to transform the Association
to a List
:
li = as /. (Association | Rule) -> List
{{{5, 2, 1}, 3}, {{6, 1, 4}, 9}, {{5, 1, 9}, 12}, {{5, 2, 4}, 6}, {{6, 2, 8}, 10}}
li = GatherBy[li /. {{_, a_, _}, b_} :> {a, b}, First]
{{{2, 3}, {2, 6}, {2, 10}}, {{1, 9}, {1, 12}}}
Association @ MapThread[Rule, {Map[#[[1, 1]] &, li], Total /@ Map[Last, li, {2}]}]
<|2 -> 19, 1 -> 21|>
Is there a way to get this result without destroying the Association
?
keyGroupBy[#[[2]]&]
composed withTotal
: mathematica.stackexchange.com/questions/59237/… $\endgroup$