Search code examples
kdb

Error when passing symbol as argument in a function for fby in kdb


length error when passing symbol as argument to a function for fby.

Syntax: (aggr;data) fby group

I have a table:

 t:([] sym:10?`IBM`AMZN`MSFT; mkt:10?`m1`m2`m3; px:10?100.)

When trying to run below it fails with length error

{select from t where px=(min;px) fby x}`sym

How to pass group as an argument to a function?


Solution

  • The sym variable (i.e. the column sym) is not in the context (as it normally would be in a select statement), because you are passing it in from outside the select statement. So here you are just passing in a variable of symbol-type with content "sym" (hence the length error). The following works, passing in the column t[`sym]:

    {select from t where px=(min;px) fby x}[t`sym]
    

    If your intention is to group by various columns, you may want to look at using functional select. e.g.

    ?[t;enlist (=;`px;(fby;(enlist;min;`px);`sym));0b;()]
    sym  mkt px      
    -----------------
    MSFT m2  17.80839
    AMZN m1  30.17723
    IBM  m2  41.1597
    

    Or passing the column name through to a function:

    {?[t;enlist (=;`px;(fby;(enlist;min;`px);x));0b;()]}`sym