Wolfram Research

Function Repository Resource:

KeyCombine

Source Notebook

Map a function over the keys of an association, and collect or combine values in the event of key collisions

Contributed by: Szabolcs Horvát

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.

Details and Options

ResourceFunction["KeyCombine"] works analogously to KeyMap, but it combines values instead of discarding them in the event of key collisions.

Examples

Basic Examples

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|>]
Out[1]=

Sum values instead of collecting them:

In[2]:=
ResourceFunction[
 "KeyCombine"][Sort, <|{1, 2} -> 10, {2, 1} -> 5, {1, 3} -> 30|>, Total]
Out[2]=

Applications

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]
Out[3]=
In[4]:=
ResourceFunction["KeyCombine"][3 Quotient[#, 3] &, counts, Total]
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];
In[6]:=
undirectedWeights = ResourceFunction["KeyCombine"][Sort /* Apply[UndirectedEdge], edgeWeights, GeometricMean]
Out[6]=
In[7]:=
Graph[VertexList[g], Keys[undirectedWeights], EdgeWeight -> Normal[undirectedWeights]]
Out[7]=

Properties and Relations

KeyCombine does not change the ordering of keys:

In[8]:=
ResourceFunction[
 "KeyCombine"][#^2 &, <|-1 -> 1, 0 -> 2, 1 -> 3, 2 -> 4|>]
Out[8]=

Resource History

Source Metadata

See Also

License Information