Search code examples
kdbq-lang

Adding Columns in kdb based on other columns value


I have a column like this in dataframe named test:

Name    Client
 A       P
 B       Q
 C       R
 D       S
 E       T

I need to to create a new column clienttype in the same dataframe with condition that, if Client = P or Q clienttype = first. If client type = R or S clienttype = second and so on. Can anyone tell how to do this in kdb? Thanks


Solution

  • Could this be solved with a dictionary?

    q)update ClientType:(`P`Q`R`S!`first`first`second`second)Client from tab
    Name Client ClientType
    ----------------------
    A    P      first
    B    Q      first
    C    R      second
    D    S      second
    E    T
    

    Extension to this: You can also use vector conditionals ?[;;] for these types of problems. Unfortunately in this case in would result in many nested vector conditionals:

    update Clienttype:?[Client in`P`Q;`first;?[Client in`R`S;`second;`third]]from tab
    Name Client Clienttype
    ----------------------
    A    P      first
    B    Q      first
    C    R      second
    D    S      second
    E    T      third
    

    If you only had two possible options (e.g. first and second) this approach could prove useful.