Search code examples
kdb

How do I write a function that consumes columns in a query in KDB?


I've got a query of the form:

select lR cor mR from j

This works fine, and I get a single number.

When I try to use my custom function:

center:{x - avg raze x}

fit1:{
  xc: 0^center[x];
  yc: 0^center[y];
  beta: raze yc lsq xc;
  intercept: (avg raze y) - (beta * avg raze x);
  raze beta
  }


select fit1[lR;mR] from j

I get a column of numbers, as it appears to have applied the function row-wise, rather than column wise.

Two questions:

  • How can I go about fixing this?
  • Is it possible to see the source code of cor so I can learn, or is it closed?

Edit

t:([] date:tt; x:xx; y:yy)

t          x y
--------------
2021.01.01 0 4
2021.01.02 1 4
2021.01.03 2 4
2021.01.04 3 4
2021.01.05 4 4
2021.01.06 5 4
2021.01.07 6 4
2021.01.08 7 4
2021.01.09 8 4
2021.01.10 9 4

select fit1[x;y] from t

Updated now with a proper example:

center:{x - avg raze x}

fit1:{
  xc: 0^center[x];
  yc: 0^center[y];
  beta: raze yc lsq xc;
  intercept: (avg raze y) - (beta * avg raze x);
  raze beta
  }

tt: 2021.01.01 + til 10
xx: 9h$til 10
yy: ((xx)*3) + 4
t:([] date:tt; x:xx; y:yy)
    date       x y
---------------
2021.01.01 0 4
2021.01.02 1 7
2021.01.03 2 10
2021.01.04 3 13
2021.01.05 4 16
2021.01.06 5 19
2021.01.07 6 22
2021.01.08 7 25
2021.01.09 8 28
2021.01.10 9 31

q)fit1[enlist xx;enlist yy]
,3f
q)select fit1[x;y] from t
y
----
-4.5
-3.5
-2.5
-1.5
-0.5
0.5
1.5
2.5
3.5
4.5

d


Solution

    1. I don't think there is enough information provided to help give a definitive fix for your issue but your function creates an intercept variable which it doesn't use in the final return. This line is currently pointless. Your custom function is not designed to return an atom like cor.

    2. Some keywords provide the underlying k code if you just enter the keyword in the q console. If you get the key word back then it is hidden but for cor and cov the equivalent code is provided in the docs.

    https://code.kx.com/q/ref/cor/ https://code.kx.com/q/ref/cov/