4
$\begingroup$

Let's consider the following simple data list

data = {{0.516393, 0.0655738, 1.92, 0.0281531, 9}, 
        {0.811475, 0.639344, 0.67, 0.00546318, 1}, 
        {-0.286885, 0.203279, 0.1, 0.0104138, 1}, 
        {1.22131, 0.839344, 0.7, 0.0037756, 3}, 
        {0.745902, 0.462295, 0.81, 0.0046604, 2}, 
        {-0.0737705, 0.396721, 0., 0.0343436, 2}, 
        {-1.07377, 0.67541, 1.32, 0.0159418, 1}, 
        {-0.893443, 0.0557377, 1.76, 1.14265, 9}, 
        {-0.336066, 0.360656, 0.1, 0.0110171, 0}, 
        {-0.106557, 0.00983607, 16.71, 0.0000678431, 1}}

I use the following code

SelectFirst[data, ((-1.1 < #[[1]] < 1.1) && (#[[5]] == 1 || #[[5]] == 2 || #[[5]] == 3)) &];

for selecting the first row of the list with given conditions.

Now how can I obtain the last row of the list with the same conditions? In other words, is there any custom made SelectLast?

$\endgroup$
0

1 Answer 1

7
$\begingroup$

You can use SelectFirst with Reversed first argument:

SelectFirst[Reverse @ data, 
  ((-1.1 < #[[1]] < 1.1) && (#[[5]] == 1 || #[[5]] == 2 || #[[5]] == 3)) &]

{-0.106557, 0.00983607, 16.71, 0.0000678431, 1}

You can make it a function similar to SelectFirst:

selectLast[criterion_] := SelectFirst[criterion] @* Reverse
selectLast[d_, criterion_] := selectLast[ criterion] @ data

selectLast[ ((-1.1 < #[[1]] < 1.1) && (#[[5]] == 1 || #[[5]] == 2 || #[[5]] == 3)) &]@data

{-0.106557, 0.00983607, 16.71, 0.0000678431, 1}

selectLast[data, ((-1.1 < #[[1]] < 1.1) && (#[[5]] == 1 || #[[5]] == 2 || #[[5]] == 3)) &]

{-0.106557, 0.00983607, 16.71, 0.0000678431, 1}

$\endgroup$
1
  • 2
    $\begingroup$ Thank you! I believe that SelectLast should also be included in the built-in functions of Mathematica. $\endgroup$
    – Vaggelis_Z
    Jul 11, 2019 at 13:32

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.