Q / KDB - nprev function to get all previous n elements

I am trying to write a function nprevin KDB; The function xprevreturns the nth element, but I need all prev elements nrelative to the current element.

q)t:([] i:1+til 26; s:.Q.a)

q)update xp:xprev[3;]s,p:prev s from t

Any help is greatly appreciated.

+4
source share
2 answers

The function xprevbasically looks like this:

xprev1:{y til[count y]-x}    //readable xprev

We can customize it to get all the items. n

nprev:{y til[count y]-\:1+til x}

using nprevin request

q)update np: nprev[3;s] , xp1:xprev1[3;s] , xp: xprev[3;s], p:prev[s]  from t
i  s np    xp1 xp p
-------------------
1  a "   "         
2  b "a  "        a
3  c "ba "        b
4  d "cba" a   a  c
5  e "dcb" b   b  d
6  f "edc" c   c  e

k equivalent nprev

k)nprev:{$[0h>@y;'`rank;y(!#y)-\:1+!x]}

and similarly it nnextwill look like

k)nnext:{$[0h>@y;'`rank;y(!#y)+\:1+!x]}
+6
source

You can achieve the desired result by repeatedly clicking prevand turning the result over

q)n:3
q)select flip 1_prev\[n;s] from t
s
-----
"   "
"a  "
"ba "
"cba"
"dcb"
"edc"
..

If nmuch less than the number of rows, it will be faster than some of the simpler solutions.

+3
source

Source: https://habr.com/ru/post/1695658/


All Articles