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 (2) 

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 (2) 

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[4]=

Properties and Relations (2) 

TallyBy is related to Tally:

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

TallyBy is related to CountsBy:

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

Publisher

SHuisman

Version History

  • 1.0.0 – 23 July 2019

License Information