Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Select for Conditional Query in Mathematica

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

like image 389
500 Avatar asked Nov 27 '22 22:11

500


2 Answers

Alternatively, using Select

Select[list, #[[2]] > 3 &]

Output

{{5, 6, 7, 8}}
like image 106
681234 Avatar answered Dec 04 '22 09:12

681234


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 from
  • index : column index for compare
  • value : the value to compare to
  • range : the Part specification to extract from each result row
like image 32
Mr.Wizard Avatar answered Dec 04 '22 09:12

Mr.Wizard