2
$\begingroup$

I want to compare elements in a list that looks like this

{{{4, 1}}, {{1, 2}}, {{1, 3}}, {{2, 4}}, {{2, 5}}, {{2, 6}}, {{1, 
7}}, {{4, 8}}, {{1, 9}}, {{4, 10}}, {{2, 11}}, {{4, 12}}, {{4, 
13}}, {{2, 14}}, {{2, 15}}, {{1, 16}}, {{4, 17}}, {{2, 18}}, {{2, 
19}}, {{1, 20}}, {{1, 21}}, {{4, 22}}, {{4, 23}}, {{1, 24}}, {{2, 
25}}, {{1, 26}}, {{4, 27}}, {{4, 28}}, {{4, 29}}, {{4, 30}},.....

I want to select the smalest (first) number b in the pair {a,b} where a will be greater than 4.

$\endgroup$
2
  • 1
    $\begingroup$ Cases[data, {{a_, b_}} /; a > 4 :> b, 1, 1]? But none of the entries in your list meet the criterion (all a are less than or equal to 4). $\endgroup$
    – Michael E2
    May 26, 2018 at 16:47
  • $\begingroup$ thank you this worked @MichaelE2 $\endgroup$
    – Fanny
    May 26, 2018 at 16:52

4 Answers 4

4
$\begingroup$

I added two entries with a > 4:

data = {{{4, 1}}, {{1, 2}}, {{1, 3}}, {{2, 4}}, {{2, 5}}, {{2, 6}}, {{1, 7}},
   {{5, 123}},
   {{4, 8}}, {{1, 9}}, {{4, 10}}, {{2, 11}}, {{4, 12}}, {{4, 13}}, {{2, 14}},
   {{6, 456}},
   {{2, 15}}, {{1, 16}}, {{4, 17}}, {{2, 18}}, {{2, 19}}, {{1, 20}}, {{1, 21}},
   {{4, 22}}, {{4, 23}}, {{1, 24}}, {{2, 25}}, {{1, 26}}, {{4, 27}}, {{4, 28}},
   {{4, 29}}, {{4, 30}}};

Then are several options (uncomment First to get the number by itself):

(*First@*) Cases[data, {{a_, b_}} /; a > 4 :> b, 1, 1]
(*  {123}  *)

A couple more:

FirstCase[data, {{a_, b_}} /; a > 4 :> b]
Select[data, #[[1, 1]] > 4 &, 1][[1, 1, 2]]
(*  123  *)
$\endgroup$
1
$\begingroup$

Here's my go

Elements:

x = Table[RandomInteger[30], 10, 2]

x={{4,6},{0,7},{0,2},{12,9},{2,19},{28,6},{10,12},{19,4},{30,29},{19,5}}

SelectFirst[SortBy[x, #[[2]] &], #[[1]] > 4 &]

Which gives {19,4}

Wasn't too sure, hopefully this meets the condition of "First smallest 'b'"

$\endgroup$
1
$\begingroup$

We could also use LengthWhile embedded in Part:

data[[LengthWhile[data, #[[1, 1]] < 5 &] + 1]]

{{5, 123}}

$\endgroup$
1
$\begingroup$

Using GroupBy:

First@GroupBy[data, #[[1, 1]] > 4 &][True]

(*{{5, 123}}*)

Or using FirstPosition and Extract:

Extract[#, FirstPosition[#, {{a_, b_}} /; a > 4]] &@data

(*{{5, 123}}*)
$\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.