kdb

How can I dynamically update column names within a function?


I built a table selector that can produce many tables from a master table by filtering on a specific column that I desire with the required values.

I would like the columns of the table, i.e. 'requests'deals'users, to be dynamic based on the value inputted into the function through variable fltr. So if I ran the below line:

fn[tabl;enlist 'Method;enlist 'Electronic];

Then this would filter the master table and return a table with three columns that have the following names: 'requestsElectronic'dealsElectronic'usersElectronic.

I have attempted different variations of string and sv with iterators and keep receiving a mismatched types error.

Any help would be greatly appreciated!


Solution

  • You can filter table column names using like (https://code.kx.com/q/ref/like):

    q)tabl:flip`col1`col2`requestsElectronic`dealsElectronic`usersElectronic!(`a`b;1 2;01b;01b;01b)
    q)fltr:`Electronic
    q){x where x like "*",string[y],"*"}[cols tabl;fltr]
    `requestsElectronic`dealsElectronic`usersElectronic
    

    You can then either replace the hard-coded list of columns in your where clause with this result or select these columns from the table using take (#):

    q)#[;tabl]{x where x like "*",string[y],"*"}[cols tabl;fltr]
    requestsElectronic dealsElectronic usersElectronic
    --------------------------------------------------
    0                  0               0
    1                  1               1
    

    Hope this helps