kdb apply function in select by row
Asked Answered
S

2

6

I have a table

t: flip `S`V ! ((`$"|A|B|"; `$"|B|C|D|"; `$"|B|"); 1 2 3)

and some dicts

t1: 4 10 15 20 ! 1 2 3 5;
t2: 4 10 15 20 ! 0.5 2 4 5;

Now I need to add a column with values on the the substrings in S and the function below (which is a bit pseudocode because I am stuck here).

f:{[s;v];
    if[`A in "|" vs string s; t:t1;];
    else if[`B in "|" vs string s; t:t2;];
    k: asc key t;
    :t k k binr v;
}

problems are that s and v are passed in as full column vectors when I do something like

update l:f[S,V] from t;

How can I make this an operation that works by row? How can I make this a vectorized function? Thanks

Scuffle answered 13/2, 2018 at 6:35 Comment(2)
it is. edited, thanks for pointing outScuffle
no worries more as an aside interesting use case for sorted attribute on dictionary instead of your k: asc key t;:t k k binr v; (although tricky with binr) v:4 5 10 13 20 21;t:`s#reverse neg[4 10 15 20]! 1 2 3 5 //neg as binr;t neg v 1 2 2 3 5 0NEuphonium
R
5

You will want to use the each-both adverb to apply a function over two columns by row.

In your case:

update l:f'[S;V] from t;
Ravelment answered 13/2, 2018 at 6:51 Comment(0)
M
1

To help with your pseudocode function, you might want to use $, the if-else operator, e.g.

f:{[s;v]
  t:$["A"in ls:"|"vs string s;t1;"B"in ls;t2;()!()];
  k:asc key t;
  :t k k binr v;
 };

You've not mentioned a final else clause in your pseudocode but $ expects one hence the empty dictionary at the end.

Also note that in your table the columns S and V have been cast to a symbol. vs expects a string to split so I've had to use the stringoperation - this could be removed if you are able to redefine your original table.

Hope this helps!

Marcomarconi answered 13/2, 2018 at 10:5 Comment(1)
ah, so, the dollar is an if-else-if-else-...-else, like a nested ?[c1;r1;;?[c2;r2;?[....]]]. That s quite useful to know, thanksScuffle

© 2022 - 2024 — McMap. All rights reserved.