# Getting the number of frequency in a list

I want to know how to make a tally board in a specific data appear in a list. E.G.

n ={1,2,1,4,3,1,4,5,3,2,4,5,6,3,4,2,2,5,2}


and get

Case        1  2  3  4  5  6  n
Frequency   3  5  3  4  3  1  19


Hoping for an answer thanks a lot!

• Possible duplicate of mathematica.stackexchange.com/questions/60185/…
– eldo
Sep 20, 2014 at 8:46
• @Mr.Wizard I think the OP requested here a specific formatting that includes not only Tally but also sorting, TableHeadings, calculate Length of the dataset and probably TableForm or similar. There is significant overlap, but its not an exacte duplicate Sep 20, 2014 at 10:39
• To @jobert I would recommend to take the tour and understand what is a duplicate. Also you could edit your question to make it more specific and a better question. Sep 20, 2014 at 10:46
• @rhermans While I saw that part as incidental since you chose to focus on it I shall reopen the question. Sep 20, 2014 at 11:04
• Related: (9801), (30859) Sep 20, 2014 at 11:05

n ={1,2,1,4,3,1,4,5,3,2,4,5,6,3,4,2,2,5,2};


To get the Tally list:

Tally[n]


To format it into a Tally Table we use TableForm:

Block[{t = Tally[n]},
TableForm[t, TableHeadings -> {None, {"Number", "Frequency"}}]
]


It happens now that its not sorted, nor in the orientation you wanted so we use SortBy, First and Transpose. Also include the total number of cases at the end

Block[
{tally, table},
tally = SortBy[Tally[n], First];
table = Transpose@Append[tally, {"n", Length@n}];
TableForm[table, TableHeadings -> {{"Case", "Frequency"}, None}]]


Which is the format the OP requested.

There is also ... EmpiricalDistribution:

lst = {1, 2, 1, 4, 3, 1, 4, 5, 3, 2, 4, 5, 6, 3, 4, 2, 2, 5, 2};

dist = EmpiricalDistribution[lst];
tally = {#["Domain"], #["SampleSize"] #["Weights"]} &[dist];
Transpose[tally] == Sort@Tally[lst]
(* True *)
TableForm[tally, TableHeadings -> {{"values", "frequency"}, None}]


tally2 = {Join @@ {#["Domain"], {"nobs"}},
Join @@ {#["SampleSize"] #["Weights"], {#["SampleSize"]}}} &[dist];
TableForm[tally2, TableHeadings -> {{"values", "frequency"}, None},
TableAlignments -> Center]


• nice use of EmpiricalDistribution Sep 20, 2014 at 15:41

Tally is the function you need.

n = {1, 2, 1, 4, 3, 1, 4, 5, 3, 2, 4, 5, 6, 3, 4, 2, 2, 5, 2};
Tally[n]


produces:

{{1, 3}, {2, 5}, {4, 4}, {3, 3}, {5, 3}, {6, 1}}


You can use Count for a specific element. Other ways to tally:

{#,Count[n, #]} & /@ Union[n]


Or

Last@Reap[Sow[1, #] & /@ n, _, {#1, Total@#2} &]

CountsBy[n, Identity] // Dataset


Update thanks to RunnyKines comment:

Dataset @ Counts @ n


does the same job more elegantly

• I know this question is a duplicate but you can use Counts instead i.e. Dataset @ Counts @ n Sep 20, 2014 at 9:09