# Finding max, min, and closest root of two dimensional data

I have some data that is two dimensional (traditional (x, y) format) as so:

var = {{x1, y1}, {x2, y2}, {x3, y3}}


I would like to search through that large list and find the maximum and minimum y values and return the ordered pair. Something like:

min[var]->{x2, y2} //read "->" as returns {the minimum ordered pair}
max[var]->{x3, y3} //read "->" as returns {the maximum ordered pair}


Finally I know the data has a "root". A plot of the points cross the x-axis. I would like to find the closest few (maybe 3 or 4) points to zero. Questions similar to this have been posted but I cannot figure out how to adapt those solutions to my needs

previous work 1

previous work 2

• You overlooked this, which may be more useful to you. – whuber May 7 '13 at 22:13
• How about var[[Ordering[var[[All, 2]]][]]] and var[[Ordering[var[[All, 2]]][[-1]]]]? – Sjoerd C. de Vries May 7 '13 at 22:27

You can define your own function with which to sort a list. For instance:

tab=Table[{Random[] - 0.5, Random[] - 0.5}, {n, 20}]
sorted=Sort[tab,#2[]^2>#1[]^2&]


This will give you a list where the elements with x closest to 0 will be first. You can take the number of desired values from this list.

For the element with the highest and lowest y element, you can use @Sjoerd C. de Vries' example in the comment, or you can define your own ordering:

sortedminmaxy=Sort[tab,#2[]>#1[]&]


and this will have the data ordered by the y value. You can then take the first and last elements as you wish.

Using the pattern I described here, define

MaxBy[list_, fun_] := list[[First@Ordering[fun /@ list, -1]]]
MinBy[list_, fun_] := list[[First@Ordering[fun /@ list, 1]]]


then do

MinBy[data, Last] (* smallest y *)
MaxBy[data, Last] (* largest y *)
MinBy[data, Composition[Abs, Last] ] (* closest to 0 *)