Function Repository Resource:

KeyGroupBy

Source Notebook

Apply a function to keys of an Association and group results by modified keys

Contributed by: Ting Sun

ResourceFunction["KeyGroupBy"][<|k1v1,k2v2,|>,f]

gives an association that groups the kivi associations with distinct keys f[ki].

ResourceFunction["KeyGroupBy"][<|k1v1,k2v2,|>,{fs1,fs2,}]

groups into nested associations using fsi at level i.

ResourceFunction["KeyGroupBy"][<|k1v1,k2v2,|>,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.

Details and Options

ResourceFunction["KeyGroupBy"] is similar to GroupBy, but operates on keys rather than values.

Examples

Basic Examples (1) 

Group keys by their leading letters:

In[1]:=
ResourceFunction["KeyGroupBy"][<|"a1" -> 1, "a3" -> 2, "b2" -> 3|>, StringTake[#, {1}] &]
Out[1]=

Scope (3) 

Create an Association for testing:

In[2]:=
asscTest = <|"xy1" -> 43, "xy2" -> 212, "xz2" -> 112|>;

Group the elements repeatedly by applying several functions onto their keys:

In[3]:=
ResourceFunction[
 "KeyGroupBy"][asscTest, {StringTake[#, {2}] &, StringTake[#, {1}] &}]
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]
Out[4]=

Applications (1) 

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]
Out[3]=
In[6]:=
ResourceFunction["KeyGroupBy"][assocFlat, {#[[2]] &, #[[1]] &}]
Out[6]=

Possible Issues (1) 

KeyGroupBy only works with Association:

In[7]:=
ResourceFunction[
 "KeyGroupBy"][{"xy1" -> 43, "xy2" -> 212, "xz2" -> 112}, StringTake[#, {1}] &, Identity]
Out[7]=

Publisher

Ting Sun

Version History

  • 2.0.0 – 23 December 2020
  • 1.0.0 – 06 May 2020

Related Resources

Author Notes

13 Dec 2020: Fix a bug in last version that the operator form with a single classifier function lacks matching rule.


License Information