Makif
Makif

Reputation: 115

Kdb generate a new column from a column of 1,-1 and null, it should generate fills 1s and -1s but it should have 0ss if the direction changes

I have a table t: ([] dir: 0n 1 0n 0n -1 0n 0n 0n 1 1 -1 0n -1 0n)

I want to generate a new column based on dir it should basicly fills the null values however I dont want the newDir column to change from 1 to -1 immediately and vice versa, if the direction changes it should be zero (for the first change direction input). So for example the resulting column should be like this:

t: ([] newDir: 0 1 1 1 0 0 0 0 1 1 0 0 -1 -1)

How can I achive this new column in kdb?

The fills method does not solve the problem obviously. I also tried to get the direction changes but I could not achieve the result because assume that I have the following input 1 0n -1 0n 1 I would like to get 1 1 0 0 1 . If I update every direction change to 0 then I would get 1 1 0 0 0 but since the first direction change only make the direction 0 it should not affect the next 1 or -1.

Upvotes: 0

Views: 93

Answers (2)

terrylynch
terrylynch

Reputation: 13657

You could create a custom "fills" using scan

q)update newDir:0f^{$[0=x+y;0f;x^y]}\[dir]from t
dir newDir
----------
    0
1   1
    1
    1
-1  0
    0
    0
    0
1   1
1   1
-1  0
    0
-1  -1
    -1

Upvotes: 1

Thomas Smyth
Thomas Smyth

Reputation: 5644

This gets the same output you expect. You can use differ to find only the values that change and then get a running sum on that:

update newDir:sums ?[differ dir;dir;0n] from t
dir newDir
----------
    0
1   1
    1
    1
-1  0
    0
    0
    0
1   1
1   1
-1  0
    0
-1  -1
    -1

Upvotes: 1

Related Questions