Search code examples
kdb

separating the records in a kdb table


There is a table with a column that I would like to break into multiple records. For example

q)tab:([]a:1 2 3;b:(`a;`$"b c";`d);c:2 3 4)
q)tab
a b   c
-------
1 a   2
2 b c 3
3 d   4

There is a space between b and c in the second entry of column b, I would like the table to become

a b c
-----
1 a 2
2 b 3
2 c 3
3 d 4

I tried

" " string vs exec b from tab

but didn't work.

Any idea?


Solution

  • Since b is the column with multiple entries per row, you can count each value and expand the corresponding row entries accordingly. Then ungroup like Terry mentioned should work.

    q)t:([]a:1 2 3;b:(`a;`b`c;`d);c:2 3 4)
    q)![t;();0b;{x!(enlist({(count each x)#'y};`b)),/:x}cols t]
    a   b    c
    ------------
    ,1  ,`a  ,2
    2 2 `b`c 3 3
    ,3  ,`d  ,4
    q)ungroup ![t;();0b;{x!(enlist({(count each x)#'y};`b)),/:x}cols t]
    a b c
    -----
    1 a 2
    2 b 3
    2 c 3
    3 d 4
    

    EDIT: Realised after your comment that the input is different. I think this is what you want.

    q)t:([]a:1 2 3;b:(`a;`$"b c";`d);c:2 3 4)
    q)ungroup update`$" "vs'string b from t
    a b c
    -----
    1 a 2
    2 b 3
    2 c 3
    3 d 4