function return a table in kdb/q
function return a table in kdb/q
I'm new in kdb/q and I'm not familiar with kdbq function, hope someone can help me. Here is the question:
I have a simple q function declared as the following:
func:{[x;y] x+y}
And {[x;y] x+y}[3;4]
gives me the answer 7
. Everything works perfectly.
{[x;y] x+y}[3;4]
7
If I have a table t
with two columns such as:
t
_x _y
--------
3 4
2 5
6 2
...
Could I have a function in q such that compute x+y
for each row of tablet
?
And my expected return would be something like:
x+y
t
res
---
7
7
8
...
Thanks so much!
2 Answers
2
You can just pass the column names as parameters to the function:
q)tab:(x:1 2 3;y:4 5 6)
q)func:{[x;y] x+y}
q)
q)select res:func[x;y]from tab
res
---
5
7
9
Alternatively you could use functional form to turn that query into a function:
q){?[x;();0b;enlist[`res]!enlist(`func;y;z)]}[tab;`x;`y]
res
---
5
7
9
Its working with the functional form of selects, which is described in decent detail on the wiki. To see what functional form looks like for a query you can run
parse"select res:func[x;y]from tab"
which will output the 4 parameters required to make up the query.– Thomas Smyth
Jun 29 at 16:03
parse"select res:func[x;y]from tab"
Thanks so much! One more quick question: i have a function
func:{[id;time] select last synp from synp_t where instr_id = id, tp_time < time}
; but when I run func[8 1;05:01:06 05:06:01]
, it gives me 'length ERROR.. do you know where I was wrong..?– Chenrui Su
Jun 29 at 16:07
func:{[id;time] select last synp from synp_t where instr_id = id, tp_time < time}
func[8 1;05:01:06 05:06:01]
Since +
is overloaded to work with both atom and list , res:func[x;y]
will work perfectly fine; however in cases when a dyadic function only accepts the arguments as atoms rather than lists then each-both
will do the trick:
+
res:func[x;y]
each-both
q)select res:func'[x;y] from tab // using each-both func'[x;y]
res
---
5
7
9
e.g To select as many charecters as c
from column s
c
s
tab2:( c:1 2 3;s:("123";"1234";"123456"))
q)update res:#'[c;s] from tab2 //func'[x;y]
c s res
-----------------------
1 "123" enlist "1"
2 "1234" "12"
3 "123456" "123"
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That's aweson! Could you explain the second alternative to me>? I don't quite get it..
– Chenrui Su
Jun 29 at 15:59