Function Repository Resource:

GroupByList

Source Notebook

Group elements according to a list of equivalence classes

Contributed by: Carl Woll

ResourceFunction["GroupByList"][{elem1,elem2,},{equiv1,equiv2,}]

gives an association that groups the elemi into lists associated with distinct keys equivi.

ResourceFunction["GroupByList"][{elem1,elem2,}, {equiv1, equiv2,} ,red]

applies the function red to reduce lists of values that are generated.

Details and Options

ResourceFunction["GroupByList"][list,equiv] gives an Association whose keys are the distinct equivi and whose values are sublists of the list list.
ResourceFunction["GroupByList"][f/@data,g/@data] is equivalent to GroupBy[data,fg].
The association keys equivi are ordered according to their first appearance in the list of equivalence classes.

Examples

Basic Examples (1) 

Group elements based on their equivalence classes:

In[1]:=
ResourceFunction["GroupByList"][Range[10], PrimeQ @ Range[10]]
Out[1]=

Scope (2) 

Consider two datasets:

In[2]:=
SeedRandom[1]
left = RandomInteger[10, 10]
Out[3]=
In[4]:=
right = RandomInteger[10, 10]
Out[4]=

Group the positions by the relative order of left and right:

In[5]:=
ResourceFunction["GroupByList"][Range @ Length @ left, Sign[right - left]]
Out[5]=

Applications (2) 

Find all partitions of the list {a,b,c,d,e} with sublists of length 2, 2 and 1. The possible permutations are:

In[6]:=
perms = Permutations @ {1, 1, 2, 2, 3}
Out[6]=

Each permutation gives an equivalence class of the list:

In[7]:=
Table[KeySort @ ResourceFunction["GroupByList"][{a, b, c, d, e}, perm], {perm, perms}]
Out[7]=

Properties and Relations (2) 

GroupByList uses a list of equivalence classes:

In[8]:=
ResourceFunction["GroupByList"][Range[10], PrimeQ[Range[10]]]
Out[8]=

GroupBy uses a equivalence function:

In[9]:=
GroupBy[Range[10], PrimeQ]
Out[9]=

GroupByList[f/@data,g/@data] is equivalent to GroupBy[data,fg]. Using GroupByList:

In[10]:=
SeedRandom[1]
data = RandomInteger[100, 10];
ResourceFunction["GroupByList"][data^2, Mod[data, 6]]
Out[12]=

Using GroupBy:

In[13]:=
GroupBy[data, Function[Mod[#, 6]] -> Function[#^2]]
Out[13]=

Publisher

Carl Woll

Version History

  • 1.0.0 – 13 November 2019

License Information