Using the following list,
list = {{a, b, c, d}, {1, 2, 3, 4}, {5, 6, 7, 8}};
Is it possible to select the lists where the second value is >3. Desired Output below
{5, 6, 7, 8}
adjusting the following code that currently extract all the values >2 in a list
Select[#, # > 2 &] & /@ list[[2 ;;]
Sophisticated solutions for queries can be found here Conditional Data Manipulation in Mathematica
Alternatively, using Select
Select[list, #[[2]] > 3 &]
Output
{{5, 6, 7, 8}}
In this case Select
is the simplest method, but Pick
can also be useful in related problems.
list = {{a, b, c, d}, {1, 2, 3, 4}, {5, 6, 7, 8}};
Pick[list, #>3& /@ list[[All, 2]] ]
To explain, Pick
takes two lists (or nested lists) of the same shape, and returns every element from the first for which the corresponding element of the second is True
. (It can also accept a third argument to match for elements other than True
.)
Here, the second column is extracted with list[[All, 2]]
and then the test #>3&
is mapped to each element. This is then used as the selection list.
Responding to the comments by 500 requesting a generalization of the Select
method:
selectByColumn[array_, index_, value_, range_] :=
Select[array, #[[index]] > value &][[All, range]]
This allows one to specify:
array
: input array to extract fromindex
: column index for comparevalue
: the value to compare torange
: the Part
specification to extract from each result rowIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With