5
$\begingroup$

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!

$\endgroup$
1

3 Answers 3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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