3
$\begingroup$

Given a 2d array such as x={{1,2},{2,3},{3,4},{4,5},{5,6}} how would I extract all pairs where the first value is between 2 and 4 such that xpart={{2,3},{3,4},{4,5}}? I need to do this for a very large data set based on different x value constraints, 2 and 4 are just simplified expression.

$\endgroup$

3 Answers 3

3
$\begingroup$
x = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}}
x // Select[Between[First@#, {2, 4}] &]

(* {{2, 3}, {3, 4}, {4, 5}} *)
$\endgroup$
1
$\begingroup$
list = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}};

Some alternatives

Using Cases

Cases[list, {2 | 3 | 4, _}]

{{2, 3}, {3, 4}, {4, 5}}

Using SequenceSplit (new in 11.3)

Catenate @ SequenceSplit[list, {{a_, _}} /; ! Between[a, {2, 4}]]

{{2, 3}, {3, 4}, {4, 5}}

Using ReplaceAll

list /. {a_, _} /; ! Between[a, {2, 4}] :> Nothing

{{2, 3}, {3, 4}, {4, 5}}

Using Delete

p = Position[list, {a_, _} /; a < 2 || a > 4]

{{1}, {5}}

Delete[p] @ list

{{2, 3}, {3, 4}, {4, 5}}

$\endgroup$
1
$\begingroup$
x = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}};

Using Replace at level 1:

Replace[x, {a_ /; ! Between[a, {2, 4}], _} :> Nothing, {1}]

(*{{2, 3}, {3, 4}, {4, 5}}*)

Or using ReplaceList:

ReplaceList[x, {___, s : {a_ /; Between[a, {2, 4}], _}, ___} :> s]

(*{{2, 3}, {3, 4}, {4, 5}}*)
$\endgroup$

Your Answer

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

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