Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Consider the following:

data={{1,a},{10,a},{5,b},{4,c}};

In my case duplicates are defined when for {x1,y1} and {x2,y2}, y2 is equal y1. Hence in the case of data, I would get via MyFunction[data] the following result:

{{1,a},{10,a}}.

Does anyone have an idea?

share|improve this question
add comment

2 Answers 2

up vote 15 down vote accepted
Select[GatherBy[{{1, a}, {10, a}, {5, b}, {4, c}}, Last], Length[#] > 1 &]

seems to do what you want. Alternatives to this construction include:

DeleteCases[GatherBy[{{1, a}, {10, a}, {5, b}, {4, c}}, Last], {_List}]

and

DeleteCases[GatherBy[{{1, a}, {10, a}, {5, b}, {4, c}}, Last], {{__}}]
share|improve this answer
add comment

GatherBy is usually fastest, but Sow and Reap are more flexible. Here is a method using those.

data = {{5, "f"}, {10, "b"}, {10, "e"}, {6, "c"}, {3, "c"}, {6, "e"},
        {4, "a"}, {2, "c"}, {6, "f"}, {2, "g"}, {9, "e"}, {0, "d"},
        {10, "c"}, {6, "b"}, {6, "c"}};

Reap[Sow @@@ data, _, {#2,#}&][[2]] ~Cases~ {{_, __},_}
{{{5, 6}, "f"},
 {{10, 6}, "b"},
 {{10, 6, 9}, "e"},
 {{6, 3, 2, 10, 6}, "c"}}

As you can see, the output is in a somewhat different format, but one that IMHO may itself be useful. You can recover your original output with Thread, e.g. Thread /@ on the output above:

{{{5, "f"}, {6, "f"}},
 {{10, "b"}, {6, "b"}},
 {{10, "e"}, {6, "e"}, {9, "e"}},
 {{6, "c"}, {3, "c"}, {2, "c"}, {10, "c"}, {6, "c"}}}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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