# How to creates a Counts[] function that includes zero?

In the following example, I'm trying to how many times each integer 1-n appears in list 'a'. But if an element did not appear in a list, Counts[] creates an association that returns the element instead of zero. So the result is a mixed list of counts and integers, with no indication of which you're looking at.

n = 10;
a = RandomInteger[n, n]
c = Counts[a];
Table[i /. c, {i, 1, n}]

{7, 7, 0, 7, 10, 5, 3, 0, 1, 8}
{1, 2, 1, 4, 1, 6, 3, 1, 9, 1}


Is there a way to make a Counts[] function that can count zero?

Use Lookup instead of ReplaceAll:

n = 10;
SeedRandom[1]
a = RandomInteger[n,n];
c = Counts[a]

Table[i /. c, {i, 1, n}]
Lookup[c, Range[10], 0]


<|1 -> 1, 4 -> 2, 0 -> 4, 7 -> 1, 8 -> 1, 6 -> 1|>

{1, 2, 3, 2, 5, 1, 1, 1, 9, 10}

{1, 0, 0, 2, 0, 1, 1, 1, 0, 0}

• Thanks this does just what I needed. But I didn't understand your comment about ReplaceAll. I didn't use ReplaceAll. Is that function inside something I used? – Jerry Guern Jan 23 at 20:05
• @JerryGuern Jerry, i /. c is short hand for ReplaceAll[i, c] – Carl Woll Jan 24 at 19:54

Or you can use SparseArray with additive matrix assembly which may be a bit faster:

n = 1000000;
a = RandomInteger[n, n];
counts = Lookup[Counts[a], Range[1, n], 0]; // AbsoluteTiming // First

counts2 = Rest@With[{spopt = SystemOptions["SparseArrayOptions"]},
InternalWithLocalSettings[
SetSystemOptions["SparseArrayOptions" -> {"TreatRepeatedEntries" -> Total}],

SparseArray[Partition[a+1, 1] -> 1, {n+1}],

SetSystemOptions[spopt]]
]; // AbsoluteTiming // First


1.30965

0.148508

True

a = {7, 7, 0, 7, 10, 5, 3, 0, 1, 8};
Counts[a] /@ Range[10] /. Missing -> (0 &)


{1, 0, 1, 0, 1, 0, 3, 1, 0, 1}

Alternatively,

Block[{Missing = (0 &)}, Counts[a] /@ Range[10]]
`

{1, 0, 1, 0, 1, 0, 3, 1, 0, 1}