2
$\begingroup$

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?

in this case would be:

$\endgroup$
1
$\begingroup$
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}}]

enter image description here

If {A,B} and {B, A} considered "same",

TableForm[Outer[Count[lst, {##} | Reverse[{##}]] &, {A, B}, {A, B}], 
  TableHeadings -> {{A, B}, {A, B}}]

enter image description here

$\endgroup$
  • $\begingroup$ How to say it that {A,B}={B,A} and this count in the matrix for A-B as for B-A? $\endgroup$ – Ask8 Mar 14 '18 at 16:15
  • $\begingroup$ @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}}` $\endgroup$ – kglr Mar 14 '18 at 16:37
  • $\begingroup$ yes! I have an error in my table $\endgroup$ – Ask8 Mar 14 '18 at 16:41
1
$\begingroup$

Here's my one-liner suggestion:

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

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.