Wolfram Research

Function Repository Resource:

ProportionsBy

Source Notebook

Get the proportion of times that each distinct element appears in a list when evaluated with a given function

Contributed by: Richard Hennigan (Wolfram Research)

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

gives an association whose keys are the distinct values of the f[ei] and whose values give the proportion of times these f[ei] values appear.

ResourceFunction["ProportionsBy"][f]

represents an operator form of ResourceFunction["ProportionsBy"] that can be applied to an expression.

Details and Options

ResourceFunction["ProportionsBy"][{e1,e2,},f] gives an association whose keys f[ei] are in the order in which the corresponding ei first appear.
ResourceFunction["ProportionsBy"][f][expr] is equivalent to ResourceFunction["ProportionsBy"][expr,f].
ResourceFunction["ProportionsBy"] also works with heads other than List.
When given an Association, ResourceFunction["ProportionsBy"] uses the Values of the association as input.

Examples

Basic Examples

Determine the proportion of a list of integers that is EvenQ:

In[1]:=
ResourceFunction["ProportionsBy"][{1, 2, 3, 2, 1, 1}, EvenQ]
Out[1]=

Get the proportion of a list that is PrimeQ:

In[2]:=
ResourceFunction["ProportionsBy"][Range[1000], PrimeQ]
Out[2]=

Use with an Association:

In[3]:=
ResourceFunction[
 "ProportionsBy"][<|"a" -> 1, "b" -> 2, "c" -> 3, "d" -> 2, "e" -> 1, "f" -> 1|>, EvenQ]
Out[3]=

Use the operator form of ProportionsBy:

In[4]:=
primeProportions = ResourceFunction["ProportionsBy"][PrimeQ]
Out[4]=
In[5]:=
Range[1000] // primeProportions
Out[5]=

Scope

See how common each character is in a body of text while ignoring case:

In[6]:=
ResourceFunction["ProportionsBy"][
   Characters[ResourceData["Gettysburg Address"]], ToLowerCase] // ReverseSort // N
Out[6]=

Check for common words:

In[7]:=
p = TakeLargest[
  N[ResourceFunction["ProportionsBy"][
    TextWords[
     DeleteStopwords[ResourceData["On the Origin of Species"]]], ToLowerCase]], 20]
Out[7]=
In[8]:=
BarChart[Reverse[p], ChartLabels -> Automatic, BarOrigin -> Left]
Out[8]=

Visualize in a WordCloud:

In[9]:=
WordCloud[p]
Out[9]=

Properties and Relations

The result of ProportionsBy is identical to that of Proportions applied to the results of Map:

In[10]:=
ResourceFunction["ProportionsBy"][Range[1000], PrimeQ]
Out[10]=
In[11]:=
ResourceFunction["Proportions"][Map[PrimeQ, Range[1000]]]
Out[11]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

See Also

License Information