# Group matrix values by column [closed]

Original Question: I have a list {{a, 1}, {b, 3}, {c, 1}, {d, 2}, {e, 3}}. I want to be able to group the the first number in each pair that has the same second number in the pair. So i would get a list like

{{a,c},d,{b,e}} so

{a,c} is from {a,1} and {c,1}

d is from {d,2}

{b,e} is from {b,3} and {e,3}

• If you have V10+ take a look at GroupBy, otherwise GatherBy documentation. – Kuba Jun 17 '16 at 7:12
• Your update seems to change the question substantially. (It makes the answer that you accepted incorrect.) You should instead ask a new question. (BTW, it appears that answer to your new question is DeleteCases[0] /@ Transpose[matrix].) – Michael E2 Jun 20 '16 at 12:50
• Transpose[matrix] /. 0 -> Nothing – m_goldberg Jun 20 '16 at 14:09

I think I know what you need:

SortBy[GatherBy[list,Last],Last@*Last][[;;,;;,1]]/.{x_?AtomQ}->x


The result is:

{{a,c},d,{b,e}}


This will gather the elements by the last member of each small list, sort it by the index number and then throw away all the index numbers. Finally, it can change all one element list into the number itself.

Will this help directly?

• @HighPerformanceMark oh yes! I mistype it cause I'm currently typing with my tiny phone on my hand. Thanks for informing! – Wjx Jun 17 '16 at 7:32

I am not sure I understand. Here are some ways to group by last element:

list={{1, 1}, {1, 3}, {2, 1}, {2, 2}, {2, 3}}
GatherBy[list, Last]
GroupBy[list, Last]
Last@Reap[Sow[{##}, #2] & @@@ list, _, Rule]


yielding respectively:

{{{1, 1}, {2, 1}}, {{1, 3}, {2, 3}}, {{2, 2}}}

<|1 -> {{1, 1}, {2, 1}}, 3 -> {{1, 3}, {2, 3}}, 2 -> {{2, 2}}|>

{1 -> {{1, 1}, {2, 1}}, 3 -> {{1, 3}, {2, 3}}, 2 -> {{2, 2}}}


GroupBy has other useful features.

• Probably GroupBy[list, Last -> First] with skiping {} from one element lists. Not so sure about an order and its meaning. – Kuba Jun 17 '16 at 7:21
• I don't mind the extra {}. But how do i use this as a list it has the weird form <|1 -> {1, 2}, 3 -> {1, 2}, 2 -> {2}|> – MTR Jun 17 '16 at 7:28
• @MTR that is an Association (see documentation), You can "normalize" it with Normal@GroupBy[list,Last]. – ubpdqn Jun 17 '16 at 7:31
• @MTR or Values @ GroupBy[list, Last -> First] – Kuba Jun 17 '16 at 7:34