8

Suppose we have the following list

data = {{0,1},{-1,2},{5,-2},{4,4},{3,0},{-1,1},{6,0.5},{7,2},{8,-5},{9,2}}

How can we remove all elements of this list which have the same x value? For example, in the above example, the entries {-1,2} and {-1,1} should be removed, since in both of them the x value is the same (-1).

I tried DeleteDuplicates[data] but it does not work.

Many thanks in advance and Merry Christmas to all!

Vaggelis_Z
  • 8,740
  • 6
  • 34
  • 79

6 Answers6

9
Select[Counts[data[[All, 1]]]@#[[1]] == 1 &] @ data

Join @@ Select[Length@# == 1 &] @ GatherBy[data, First]

Values @ GroupBy[data, First, If[Length @ # > 1, Nothing, #[[1]]] &]

data[[Flatten @ Select[Length @ # == 1 &] @ 
   GatherBy[Range @ Length @ data, data[[#, 1]] &]]]

FixedPoint[SequenceReplace[#, b : {{a_, _}, ___, {a_, _}} :> 
    Sequence @@ DeleteCases[b, {a, _}]] &, data]

all give

 {{0, 1}, {5, -2}, {4, 4}, {3, 0}, {6, 0.5`}, {7, 2}, {8, -5}, {9, 2}}
kglr
  • 394,356
  • 18
  • 477
  • 896
6
Tally[data, First@#1 == First@#2 &] // Cases[{x_, 1} :> x]

gives

{{0, 1}, {5, -2}, {4, 4}, {3, 0}, {6, 0.5}, {7, 2}, {8, -5}, {9, 2}}
AsukaMinato
  • 9,758
  • 1
  • 14
  • 40
2
data[[Flatten[Select[Part[#,2]&/@Normal[PositionIndex[First/@data]],Length[#]>1&]]]]={"delThis"};
data=DeleteCases[data,{"delThis"}]

{{0, 1}, {5, -2}, {4, 4}, {3, 0}, {6, 0.5}, {7, 2}, {8, -5}, {9, 2}}
vi pa
  • 410
  • 2
  • 9
2
list = {{3, 4}, {0, 1}, {1, 2}, {0, 2}, {2, 1}, {2, 2}};

Using SequenceCases to find duplicated first elements

dup = SequenceCases[list, {{a_, _}, ___, {a_, _}} :> a]

{0, 2}

Select[FreeQ[dup, First[#]] &] @ list

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

eldo
  • 67,911
  • 5
  • 60
  • 168
2
data = {{0, 1}, {-1, 2}, {5, -2}, {4, 4}, {3, 0},
       {-1, 1}, {6, 0.5}, {7, 2}, {8, -5}, {9, 2}};

Grabbing the @eldo's pattern and using ReplaceList and Pick:

dup = ReplaceList[data, {___, {a_, _}, __, {a_, _}, ___} :> a]

Pick[#, FreeQ[dup, First[#]] & /@ #] &@data

{{0, 1}, {5, -2}, {4, 4}, {3, 0}, {6, 0.5}, {7, 2}, {8, -5}, {9, 2}}

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
2
GatherBy[data, First] // Select[EqualTo[1]@*Length] // Map[First]

data~GatherBy~First~Select~EqualTo[1]@*Length // Map[First]

GatherBy[data, First] // Cases[{a_List} :> a]

Replace[data, {x___, {a_, b_}, y___, {a_, c_}, z___} :> {x, y, 
   z}, All]

ReplaceRepeated[data, {x___, 
   PatternSequence[{a_, b_}, g___, {a_, c_}], y___} :> {x, g, y}]

{{0, 1}, {5, -2}, {4, 4}, {3, 0}, {6, 0.5}, {7, 2}, {8, -5}, {9, 2}}

Syed
  • 52,495
  • 4
  • 30
  • 85