2021.09.22 10:12 PM
I want to add a column to an existing table based on nested conditions
T:([]a:`F`R;b:10 20;c:9 21;d:10 22)
Func:{[tab]
If a=`F
If b<c
Add new column with value as 'hi
Else
new='welcome
Else
if c>d
new=`hi
Else
new='welcome
}
Please help.
2021.09.22 11:34 PM - edited 2021.09.22 11:36 PM
This is most easily done in two parts and then defaulting the rest to welcome:
q)T:update newCol:`hi from T where a=`F,b<c
q)T:update newCol:`hi from T where a<>`F,c>d
q)T:update`welcome^newCol from T
q)T
a b c d newCol
------------------
F 10 9 10 welcome
R 20 21 22 welcome
You may find the reference on update statements useful: https://code.kx.com/q/ref/update/
If you want it done in one line (which doesn't scale well for any additional clauses you might want):
q)update newCol:`welcome`hi any(all(a=`F;b<c);all(a<>`F;c>d))from T
a b c d newCol
------------------
F 10 9 10 welcome
R 20 21 22 welcome
2021.09.22 11:34 PM - edited 2021.09.22 11:36 PM
This is most easily done in two parts and then defaulting the rest to welcome:
q)T:update newCol:`hi from T where a=`F,b<c
q)T:update newCol:`hi from T where a<>`F,c>d
q)T:update`welcome^newCol from T
q)T
a b c d newCol
------------------
F 10 9 10 welcome
R 20 21 22 welcome
You may find the reference on update statements useful: https://code.kx.com/q/ref/update/
If you want it done in one line (which doesn't scale well for any additional clauses you might want):
q)update newCol:`welcome`hi any(all(a=`F;b<c);all(a<>`F;c>d))from T
a b c d newCol
------------------
F 10 9 10 welcome
R 20 21 22 welcome
2021.09.23 04:17 AM
Thanks Cillian.
2021.09.23 04:23 AM
Another option is to use vector conditional (?)
https://code.kx.com/q/ref/vector-conditional/
q)update new_col:?[a=`F;[?[b<c;`hi;`welcome]];[?[c>d;`hi;`welcome]]] from T
a b c d new_col
------------------
F 10 9 10 welcome
R 20 21 22 welcome
EMEA
Tel: +44 (0)28 3025 2242
AMERICAS
Tel: +1 (212) 447 6700
APAC
Tel: +61 (0)2 9236 5700
KX. All Rights Reserved.
KX and kdb+ are registered trademarks of KX Systems, Inc., a subsidiary of FD Technologies plc.