Skip to content

med

Median

med x    med[x]

Where x is a numeric list, returns its median.

q)med 10 34 23 123 5 56
28.5
q)trade:([]sym:`AAPL`LEH`AAPL`LEH`AAPL;price:10 20 12 26 11f)
q)select med price by sym from trade
sym | price
----| -----
AAPL| 11
LEH | 23

Unlike avg, med does not ignore nulls: they sort before all other values.

q)med 1 2 0N 4
1.5

med is an aggregate function, equivalent to:

{avg x (iasc x)@floor .5*-1 0+count x,:()}

Domain and range

domain: B G X H I J E F C S P M D Z N U V T
range:  f . f f f f f f f . f f f f f f f f

Implicit iteration

med applies to dictionaries and tables.

q)kt:`k xkey update k:`abc`def`ghi from t:flip d:`a`b!(10 -21 3;4 5 -6)

q)med d
7 -8 -1.5

q)med t
a| 3
b| -6

q)med kt
a| 3
b| -6

Partitions and segments

med signals a part error when you run a median over partitions or segments. This is deliberate, because the median of the medians of the partitions is not the median of the whole. Code a cascading select instead, so that the median runs on an in-memory table:

select med price by sym from
  select price, sym from trade
    where
      date within 2001.10.10 2001.10.11,
      sym in `AAPL`LEH

Mathematics