Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Map a function over the keys of an association, and collect or combine values in the event of key collisions
| ResourceFunction["KeyCombine"][f,assoc] maps f over the keys in assoc and collects values having the same key into a list. | |
| ResourceFunction["KeyCombine"][f,assoc,comb] uses the combiner function comb to combine values having the same key. | |
| ResourceFunction["KeyCombine"][f] represents an operator form of ResourceFunction["KeyCombine"] that can be applied to an expression. | 
Sort the keys of an association and collect values that end up having the same key:
| In[1]:= | ![ResourceFunction[
 "KeyCombine"][Sort, <|{1, 2} -> 10, {2, 1} -> 5, {1, 3} -> 30|>]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/7e511948e91ec841.png) | 
| Out[1]= |  | 
Sum values instead of collecting them:
| In[2]:= | ![ResourceFunction[
 "KeyCombine"][Sort, <|{1, 2} -> 10, {2, 1} -> 5, {1, 3} -> 30|>, Total]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/0ed598b15b8eaec7.png) | 
| Out[2]= |  | 
Convert frequency data (counts) created using a bin size of 1 to a bin size of 3:
| In[3]:= | ![counts = KeySort@Counts@RandomInteger[10, 100]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/59e11dff59e8f498.png) | 
| Out[3]= |  | 
| In[4]:= | ![ResourceFunction["KeyCombine"][3 Quotient[#, 3] &, counts, Total]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/1e1168445f6d0b97.png) | 
| Out[4]= |  | 
Combine reciprocal edges of a weighted, directed graph using geometric mean:
| In[5]:= | ![g = RandomGraph[{10, 30}, DirectedEdges -> True, EdgeWeight -> {_ :> RandomReal[]}];
directedWeights = Association@Most@ArrayRules@WeightedAdjacencyMatrix[g];](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/0a7703763f318cad.png) | 
| In[6]:= | ![undirectedWeights = ResourceFunction["KeyCombine"][Sort/*Apply[UndirectedEdge], edgeWeights, GeometricMean]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/6e75f1f36fe96f29.png) | 
| Out[6]= |  | 
| In[7]:= | ![Graph[VertexList[g], Keys[undirectedWeights], EdgeWeight -> Normal[undirectedWeights]]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/28daacfe9cea1bf1.png) | 
| Out[7]= |  | 
KeyCombine does not change the ordering of keys:
| In[8]:= | ![ResourceFunction[
 "KeyCombine"][#^2 &, <|-1 -> 1, 0 -> 2, 1 -> 3, 2 -> 4|>]](https://www.wolframcloud.com/obj/resourcesystem/images/fa2/fa2c6e6e-8664-409b-bfc5-a93c29fc6b01/063e841d63c9322e.png) | 
| Out[8]= |  | 
This work is licensed under a Creative Commons Attribution 4.0 International License