4

I have a list of pairs of coordinates, where some are missing.

coordinates = {
  {{1, 1}, {1, 2}},
  {{3, 4}, {5, 5}},
  {{1, 2}, Missing[]},
  {{9, 8}, {7, 7}},
  {Missing[], {2, 3}}
}

I am trying to remove the pairs containing missing coordinates, to get

coordinates = {
  {{1, 1}, {1, 2}},
  {{3, 4}, {5, 5}},
  {{9, 8}, {7, 7}},
}

I tried

coordinates = DeleteCases[coordinates, MemberQ[#, _Missing] &]

but that did not work. But the function MemberQ works on pairs directly:

MemberQ[coordinates[[1]], _Missing] (* returns False *)
MemberQ[coordinates[[3]], _Missing] (* returns True *)

What did I do wrong?

iblue
  • 143
  • 4

4 Answers4

6
coordinates = {{{1, 1}, {1, 2}}, {{3, 4}, {5, 5}}, {{1, 2}, Missing[]}, {{9, 8}, {7, 7}}, {Missing[], {2, 3}}};

The second argument to DeleteCases must be a pattern not a boolean.

correctedCoordinates = DeleteCases[coordinates, _?(MemberQ[#, _Missing] &)]

{{{1, 1}, {1, 2}}, {{3, 4}, {5, 5}}, {{9, 8}, {7, 7}}}

Similarly with Cases

correctedCoordinates == Cases[coordinates, _?(FreeQ[#, _Missing] &)]

True

Whereas, Select requires a boolean.

correctedCoordinates == Select[coordinates, FreeQ[#, _Missing] &]

True

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
  • Yes, you're right. I was mistaken about what was going wrong. Do you know what happened to MathGroup? No new messages since May 22. – Szabolcs Jun 06 '14 at 18:31
  • Presumably, most/all of the traffic migrated here and the moderator fell asleep. :-) – Bob Hanlon Jun 06 '14 at 18:54
4
DeleteCases[coordinates, {___, Missing[], ___}]

Or (slower)

Cases[coordinates, {{__?NumberQ}, {__?NumberQ}}]

I like this style because of its flexibility in more complicated cases.

With

x = Join @@ Table[coordinates, {10^5}];

Eldo DeleteCases : 0.22 sec.
Szabolcs: : 0.86 sec.
Bob Hanlon DeleteCases : 0.95 sec.

eldo
  • 67,911
  • 5
  • 60
  • 168
4

Bob Hanlon has the answer, but merely as a supplement: if your data is as you show I would simply use Select and MatrixQ.

Select[coordinates, MatrixQ]
{{{1, 1}, {1, 2}}, {{3, 4}, {5, 5}}, {{9, 8}, {7, 7}}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

You could also use DeleteMissing:

DeleteMissing[coordinates, 1, 1]

{{{1, 1}, {1, 2}}, {{3, 4}, {5, 5}}, {{9, 8}, {7, 7}}}

but it's more than 4 times slower on my PC than the solution provided in the answer by Mr.Wizard.

Karsten7
  • 27,448
  • 5
  • 73
  • 134