# How to select rows based on the entry value of the first column?

Data={{0,5678},{0,5654},{1,87675},{2,243},{2,257},{1,9790},{0,7688},{1,97779},{0,6858}}


Given a data set similar to the above, how can I select rows where the first column entry is a number that I specify, and the following row is a row is where the first column entry is another number that I specify, and only alternating first column entries, for instance,

Choose 0 Choose 1

I'd like the output to be,

{{0,5678},{1,87675},{0,7688},{1,97779}}


Or if I do

Choose 1 Choose 2

I'd like the output to be,

{{1,87675},{2,243},}


etc.

So far, I have

Cases[Data,{n_,_}/;n>=1]


This doesn't quite do it, but it's a start. Thanks!

• Something like SplitBy[Select[Data, MatchQ[{0 | 1, _}]], First][[All, 1]]? Commented Dec 25, 2020 at 3:50

### SequenceCases

Join @@ SequenceCases[data, {{0, _}, {1, _}}]

{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

Join @@ SequenceCases[data, {{1, _}, {2, _}}]

{{1, 87675}, {2, 243}}


### SequencePosition + Part

Join @@ (data[[#]] & /@ SequencePosition[data[[All, 1]], {0, 1}])

 {{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

Join @@ (data[[#]] & /@ SequencePosition[data[[All, 1]], {1, 2}])

 {{1, 87675}, {2, 243}}


### Split + Select

Join @@ Select[Length @ # >= 2 &] @ Split[data, #[[1]] == 0 && #2[[1]] == 1 &]

{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

Join @@ Select[Length @ # >= 2 &]@ Split[data, #[[1]] == 1 && #2[[1]] == 2 &]

{{1, 87675}, {2, 243}}


### Partition + Select

Join @@ Select[#[[All, 1]] == {0, 1} &] @ Partition[data, 2, 1]

{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

Join @@ Select[#[[All, 1]] == {1, 2} &] @ Partition[data, 2, 1]

{{1, 87675}, {2, 243}}


### BlockMap

BlockMap[If[#[[All, 1]] == {0, 1}, Sequence @@ #, Nothing] &, data, 2, 1]

 {{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

BlockMap[If[#[[All, 1]] == {1, 2}, Sequence @@ #, Nothing] &, data, 2, 1]

 {{1, 87675}, {2, 243}}

list =
{{0, 5678}, {0, 5654}, {1, 87675}, {2, 243}, {2, 257},
{1, 9790}, {0, 7688}, {1, 97779}, {0, 6858}};

f = Catenate @ Partition[First /@ SplitBy[Cases[list, {#, _}], First], 2] &;

f[0 | 1]


{{0, 5678}, {1, 87675}, {0, 7688}, {1, 97779}}

f[1 | 2]


{{1, 87675}, {2, 243}}

data = {{0, 5678}, {0, 5654}, {1, 87675},
{2, 243}, {2, 257}, {1, 9790},
{0, 7688}, {1, 97779}, {0, 6858}};


Using SequencePosition and Extract:

f = Extract[#1, List /@ Union @@ SequencePosition[#1, {{#2, _}, {#3, _}}]] &;

f[data, 0, 1]


{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

f[data, 1, 2]


{{1, 87675}, {2, 243}}

Or using Partition and Pick:

f[l_, {m_, n_}] :=
Join @@ Pick[#, #[[1, 1]] == m && #[[2, 1]] == n & /@ #] &@Partition[l, 2, 1]

f[data, {0, 1}]


{{0, 5654}, {1, 87675}, {0, 7688}, {1, 97779}}

f[data, {1, 2}]


{{1, 87675}, {2, 243}}