0
$\begingroup$

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?

$\endgroup$
  • 3
    $\begingroup$ That is a pretty useful type introduced in MMA 10, Association. check it out, you will like it. $\endgroup$ – Kattern Jun 6 '15 at 7:43
  • 1
    $\begingroup$ You can also use Tally e.g. Tally[Sort@nn] $\endgroup$ – ubpdqn Jun 6 '15 at 7:54
  • 2
    $\begingroup$ 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. $\endgroup$ – Stephen Luttrell Jun 6 '15 at 10:34
  • $\begingroup$ @StephenLuttrell Ah. Yes, I saw that, but I didn't realize that by "association" they were referring to a specific data structure. $\endgroup$ – Jerry Guern Jun 6 '15 at 19:52
2
$\begingroup$

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*)
$\endgroup$
  • $\begingroup$ Ah. So, you don't really need to do the Sort[] that you have in there, if I understand this correctly. $\endgroup$ – Jerry Guern Jun 6 '15 at 8:00
  • $\begingroup$ @JerryGuern Yes, no need. I just copy your code. $\endgroup$ – Kattern Jun 6 '15 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.