Search code examples
kdbq-lang

[KDB+/Q]: Nested vector conditional


How to efficiently and concisely switch formulas dependent on the value of other vector?

According to kx documentation, it is possible to

have more than just a true/false selection, e.g. match1/match2/match3/others mapping to result1/result2/result3/default

Data:

q)t:([]a:til 5;b:10+til 5;c:100+til 5;d:1000+til 5;g:`I`B`I`U`B) 
a b  c   d    g
---------------
0 10 100 1000 I
1 11 101 1001 B
2 12 102 1002 I
3 13 103 1003 U
4 14 104 1004 B

I've done it like this:

q)update r:(flip (a+b;c+d;a-d))@'`I`B`U?g from t
a b  c   d    g r    
---------------------
0 10 100 1000 I 10   
1 11 101 1001 B 1102 
2 12 102 1002 I 14   
3 13 103 1003 U -1000
4 14 104 1004 B 1108 

Question - is there more efficient way (time,space,lines of code)?


Solution

  • This is similar to your solution, but seems about 30% faster, possibly because there's no flip

    q)update r: ((a+b;c+d;a-d)@(`I`B`U?g))@'i from t
    a b  c   d    g r
    ---------------------
    0 10 100 1000 I 10
    1 11 101 1001 B 1102
    2 12 102 1002 I 14
    3 13 103 1003 U -1000
    4 14 104 1004 B 1108
    
    q)t:1000000?t
    q)\t update r: ((a+b;c+d;a-d)@(`I`B`U?g))@'i from t
    166
    q)\t update r:(flip (a+b;c+d;a-d))@'`I`B`U?g from t
    248
    

    Although the nested conditional still looks faster:

    q)\t update r:?[`I=g;a+b;?[`B=g;c+d;a-d]] from t
    46