Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Apply a function to keys of an Association and group results by modified keys
| ResourceFunction["KeyGroupBy"][<|k1→v1,k2→v2,…|>,f] gives an association that groups the ki→vi associations with distinct keys f[ki]. | |
| ResourceFunction["KeyGroupBy"][<|k1→v1,k2→v2,…|>,{fs1,fs2,…}] groups into nested associations using fsi at level i. | |
| ResourceFunction["KeyGroupBy"][<|k1→v1,k2→v2,…|>,spec,red] applies the function red to reduce sub-associations that are generated. | |
| ResourceFunction["KeyGroupBy"][spec] represents an operator form of that ResourceFunction["KeyGroupBy"] can be applied to an association. | 
Group keys by their leading letters:
| In[1]:= | ![ResourceFunction["KeyGroupBy"][<|"a1" -> 1, "a3" -> 2, "b2" -> 3|>, StringTake[#, {1}] &]](https://www.wolframcloud.com/obj/resourcesystem/images/10d/10d8ffd6-2783-4d26-949b-9636792e92ff/2b42e1d69fc6cf45.png) | 
| Out[1]= |  | 
Create an Association for testing:
| In[2]:= |  | 
Group the elements repeatedly by applying several functions onto their keys:
| In[3]:= | ![ResourceFunction[
 "KeyGroupBy"][asscTest, {StringTake[#, {2}] &, StringTake[#, {1}] &}]](https://www.wolframcloud.com/obj/resourcesystem/images/10d/10d8ffd6-2783-4d26-949b-9636792e92ff/1b3e657c4c18b06a.png) | 
| Out[3]= |  | 
Group the elements repeatedly by applying several functions onto their keys and reduce the results into their means:
| In[4]:= | ![ResourceFunction[
 "KeyGroupBy"][asscTest, {StringTake[#, {2}] &, StringTake[#, {1}] &}, Mean]](https://www.wolframcloud.com/obj/resourcesystem/images/10d/10d8ffd6-2783-4d26-949b-9636792e92ff/04f963bc39d4d283.png) | 
| Out[4]= |  | 
KeyGroupBy can be useful in reorganizing levels of a nested dataset in together with the resource function AssociationKeyFlatten:
| In[5]:= | ![assoc = <|Subscript[k, 1] -> <|Subscript[k, 11] -> a, Subscript[k, 12] -> b|>, Subscript[k, 2] -> <|Subscript[k, 21] -> <|Subscript[k, 211] -> c, Subscript[k, 212] -> d|>|>, Subscript[k, 3] -> <|Subscript[k, 31] -> b|>, Subscript[k, 4] -> <|Subscript[k, 41] -> e|>|>;
assocFlat = ResourceFunction["AssociationKeyFlatten"][assoc]](https://www.wolframcloud.com/obj/resourcesystem/images/10d/10d8ffd6-2783-4d26-949b-9636792e92ff/33f9b5f6dfa43b9a.png) | 
| Out[3]= |  | 
| In[6]:= | ![ResourceFunction["KeyGroupBy"][assocFlat, {#[[2]] &, #[[1]] &}]](https://www.wolframcloud.com/obj/resourcesystem/images/10d/10d8ffd6-2783-4d26-949b-9636792e92ff/14d4c985882b3015.png) | 
| Out[6]= |  | 
This work is licensed under a Creative Commons Attribution 4.0 International License