Search code examples
multiple-columnskdb

Reorder columns (xcols) by index KDB+/Q


I have a table below in KDB+ that I need to reorder columns for, but not by name, by Index. What I mean is that in the example table below, I don't know that the column names are "ltCt", "poPt", "kgAg", "xoOt", all I know is that the 6th column needs to be the 4th column, the 7th column needs to be the 5th column, etc., and I need to reorder them according to that.

Is it possible to reorder columns like this in KDB+? My understanding is that xcols seems to require column names.

    x         y        z            ltCt     poPt     kgAg     xoOt   
    ---------------------------------------------------------------------
    today     setting1 model1       41.66    367.69   -662.89  11347.91 

ideal output format:

    x         y        z             kgAg      xoOt       ltCt   poPt     
    ---------------------------------------------------------------------
    today     setting1 model1       -662.89    11347.91   41.66  367.69

Solution

  • You can use the keyword cols to extract the list of columns:

    q)cols tab
    `x`y`z`ltCt`poPt`kgAg`xoOt
    

    edit: You can then use the keyword rank followed by the order you would like (or supply just the indexes without rank) to reorder the column list:

    q)cols[tab] rank 1 2 3 6 7 4 5
    `x`y`z`kgAg`xoOt`ltCt`poPt
    
    q)cols[tab] 0 1 2 5 6 3 4
    `x`y`z`kgAg`xoOt`ltCt`poPt
    

    Then finally put this into xcols along with your table:

    q)(cols[tab] 0 1 2 5 6 3 4) xcols tab
    

    https://code.kx.com/q/ref/cols/

    https://code.kx.com/q/ref/rank/