Back to Updating Tables

In Memory Tables · Updating Tables · Practice Question

Add a Column Derived from Another Column

Sign in to track your progress

Question

Given a table t with a boolean column d, add a new column e such that:

For example:

t:([] sym:`A`B`C; d:010b)
  • e is `yes where d is 1b
  • e is `no where d is 0b

Solution

update e:?[d;`yes;`no] from `t

Alternative Solution

update e:(`no;`yes)[d] from `t

Alternative Solution

update e:`no`yes d from `t

Explanation

?[d;yes;no] is the vector conditional: for every row, it picks `yes if that row's d is true and `no otherwise — applied across the whole column in one call, with no explicit iterator needed.

The alternatives lean on the fact that a boolean is really just 0/1 underneath, so it can index directly into a 2-item list: (no;yes)[d] and `no`yes d both index the list (`no;`yes) (or `no`yes) using d itself — 0b selects index 0 (`no), 1b selects index 1 (`yes). This is a common q idiom for mapping a boolean column onto exactly two output values without writing a conditional at all.