Wolfram Research

Function Repository Resource:

TallyBy

Source Notebook

Tally items that give the same value when a function is applied

Contributed by: Sander Huisman

ResourceFunction["TallyBy"][{e1,e2,},f]

tallies the elements ei for which f[ei] returns the same value and returns these f[ei] values and their counts.

ResourceFunction["TallyBy"][{e1,e2,},f,g]

applies function g to each list tallied by f and returns these g[ei] values and their counts.

Details and Options

ResourceFunction["TallyBy"] lists distinct elements in the order they appear in the ei and by default returns all the items of each equivalence class.

Examples

Basic Examples

Tally but do not care about the capitalization:

In[1]:=
ResourceFunction[
 "TallyBy"][{"Adam", "berta", "adam", "Berta"}, ToLowerCase]
Out[1]=

Return only the first entry rather than all of the entries for each equivalence partition:

In[2]:=
ResourceFunction[
 "TallyBy"][{"Adam", "berta", "adam", "Berta"}, ToLowerCase, First]
Out[2]=

Applications

Tally numbers that are close to each other and only show a representative number:

In[3]:=
ResourceFunction[
 "TallyBy"][{1.0, 1, 1.0`10, 2, 3.0, 2.9, Pi, E, 0.99}, Round, Median]
Out[3]=

Tally words to find the largest anagram groups:

In[4]:=
tallies = ResourceFunction["TallyBy"][DictionaryLookup[], Sort@*Characters@*ToLowerCase, Identity];
TakeLargestBy[tallies, Last, 10]
Out[5]=

Properties and Relations

TallyBy is related to Tally:

In[6]:=
numbers = RandomInteger[{0, 5}, 150];
ResourceFunction["TallyBy"][numbers, Identity, First] === Tally[numbers]
Out[7]=

TallyBy is related to CountsBy:

In[8]:=
ResourceFunction[
 "TallyBy"][{"a", "large", "red", "car"}, StringLength]
Out[8]=
In[9]:=
CountsBy[{"a", "large", "red", "car"}, StringLength]
Out[9]=

Resource History

License Information