0

I need to create a list of the distinct elements in a list along with the number of times each appears.

The function Counts[] is supposed to do this, but it puts the results in some weird format I've never seen before and don't know how to use.

nn = RandomInteger[5, 200];
Counts[Sort[nn]];

(* <|0 -> 36, 1 -> 30, 2 -> 31, 3 -> 33, 4 -> 36, 5 -> 34|> *)

And OF COURSE the online-documentation on Counts[] doesn't cover this topic AT ALL (grumble, grumble)...

So, I hacked my own function to do the counts and put them in a nice array:

a = Gather[Sort[nn]];
Table[{a[[i, 1]], Length[a[[i]]]}, {i, 1, Length[a]}]

(* {{0, 36}, {1, 30}, {2, 31}, {3, 33}, {4, 36}, {5, 34}} *)

But what is that output format that Counts[] returns? How can I access the numbers in it?

Jerry Guern
  • 4,602
  • 18
  • 47
  • 3
    That is a pretty useful type introduced in MMA 10, Association. check it out, you will like it. – Kattern Jun 06 '15 at 07:43
  • 1
    You can also use Tally e.g. Tally[Sort@nn] – ubpdqn Jun 06 '15 at 07:54
  • 2
    The documentation for Counts says (in the Details section) "Counts[list] gives an association whose keys are in the same order as they first occur as elements of list.", so you then look up Association and all is revealed. However, I agree with you that the documentation could be improved, e.g. Wolfram should add an explicit link to Association. – Stephen Luttrell Jun 06 '15 at 10:34
  • @StephenLuttrell Ah. Yes, I saw that, but I didn't realize that by "association" they were referring to a specific data structure. – Jerry Guern Jun 06 '15 at 19:52

1 Answers1

2

This is a very connivent function introduced in Mathematica v10. The old solution of hash table is presented at: How to get the list of defined values for an indexed variable? Now you can do it with Association pretty easy.

nn = RandomInteger[5, 200];
c = Counts[nn]
(*<|1 -> 37, 4 -> 43, 0 -> 30, 3 -> 36, 2 -> 28, 5 -> 26|>*)
c[0]
(*30*)
Kattern
  • 2,561
  • 19
  • 35