# Count elements from list and order it in a matrix

I have a list ({{A,A},{A,B},{A,B},{B,B},{B,A}}) I need to order it in a matrix where elements are the number of times that each pair appear at the list. What can I do?

## 2 Answers

lst = {{A, A}, {A, B}, {A, B}, {B, B}, {B, A}};

TableForm[GatherBy[Sort@Tally[lst], #[[1, 1]] &][[All, All, -1]],
TableHeadings -> {{A, B}, {A, B}}]


Or

TableForm[Outer[Count[lst, {##}] &, {A, B}, {A, B}], TableHeadings -> {{A, B}, {A, B}}] If {A,B} and {B, A} considered "same",

TableForm[Outer[Count[lst, {##} | Reverse[{##}]] &, {A, B}, {A, B}],
TableHeadings -> {{A, B}, {A, B}}] • How to say it that {A,B}={B,A} and this count in the matrix for A-B as for B-A? – Ask8 Mar 14 '18 at 16:15
• @LinaRuiz, if "{A,B}={B,A}" (that is, {A,B} and {B,A} are "identical") then you should have 3 in (not 2) in your table, no? Tally[lst, Sort[#] == Sort[#2] &] gives{{{A, A}, 1}, {{A, B}, 3}, {{B, B}, 1}} – kglr Mar 14 '18 at 16:37
• yes! I have an error in my table – Ask8 Mar 14 '18 at 16:41

Here's my one-liner suggestion:

list = {{A, A}, {A, B}, {A, B}, {B, B}, {B, A}};
Dataset @ GroupBy[list, First -> Last, Counts]
`