Search code examples
kdb

kdb how to pass a column name into a function


As a simplifying example, I have

tbl:flip `sym`v1`v2!(`a`b`c`d; 50 280 1200 1800; 40 190 1300 1900)

and I d like to pass a column name into a function like

f:{[t;c];:update v3:2 * c from t;} 

In this form it doesnt work. any suggestion how I can make this happen? Thanks


Solution

  • One option to achieve this is using @ amend:

    q){[t;c;n] @[t;n;:;2*t c]}[tbl;`v1;`v3]
    sym v1   v2   v3
    ------------------
    a   50   40   100
    b   280  190  560
    c   1200 1300 2400
    d   1800 1900 3600
    

    This updates the column c in table t saving the new value as column n. You could also alter this to allow you to pass in custom functions too:

    {[t;c;n;f] @[t;n;:;f t c]}[tbl;`v1;`v3;{2*x}]