1

I'm currently learning kdb+/q. I have a table of data. I want to take 2 columns of data (just numbers), compare them and create a new Boolean column that will display whether the value in column 1 is greater than or equal to the value in column 2.

I am comfortable using the update command to create a new column, but I don't know how to ensure that it is Boolean, how to compare the values and a method to display the "greater-than-or-equal-to-ness" - is it possible to do a simple Y/N output for that?

Thanks.

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
Jonathan
  • 109
  • 6

3 Answers3

6
/ dummy data
q) show t:([] a:1 2 3; b: 0 2 4)
    a b
    ---
    1 0
    2 2
    3 4

/ add column name 'ge' with value from b>=a
q) update ge:b>=a from t
    a b ge
    ------
    1 0 0
    2 2 1
    3 4 1
MdSalih
  • 1,978
  • 10
  • 16
1

Use a vector conditional: http://code.kx.com/q/ref/lists/#vector-conditional

    q)t:([]c1:1 10 7 5 9;c2:8 5 3 4 9)
    q)r:update goe:?[c1>=c2;1b;0b] from t
    c1 c2 goe
    -------------
    1  8  0
    10 5  1
    7  3  1
    5  4  1
    9  9  1

Use meta to confirm the goe column is of boolean type:

  q)meta r
   c      | t f a
   -------| -----
   c1     | j
   c2     | j
   goe    | b
jomahony
  • 1,662
  • 6
  • 9
  • Fantastic, and thank you. As usual with these sorts of things, it is far simpler than I imagined. – Jonathan Jun 14 '17 at 15:23
  • 1
    For what it's worth, you don't need the vector conditional. Using the greater than operator will generate a list of booleans for you `update goe:c1>=c2 from t` – Conor Cadogan Jun 14 '17 at 21:48
0

The operation <= works well with vectors, but in some cases when a function needs atoms as input for performing an operation, you might want to use ' (each-both operator).

e.g. To compare the length of symbol string with another column value

q)f:{x<=count string y}
q)f[3;`ab]
0b

q)t:([] l:1 2 3; s: `a`bc`de)
q)update r:f'[l;s] from t
l s  r
------
1 a  1
2 bc 1
3 de 0
nyi
  • 3,123
  • 4
  • 22
  • 45