qSQL · Update · Practice Question
Derive Columns from Boolean Flags
Derive Columns from Boolean Flags
Question
Given the following table:
t:([] sym:`cfl`bpm`icj`ini`nmo`ojj`bjc`khd`hjb`lhk;
px:2.296615 6.919531 4.707883 6.346716 9.672398 2.306385 9.49975 4.39081 5.759051 5.919004;
qty:8 1 9 5 4 6 6 1 8 5)Add two new columns:
-
active- a random boolean value for each row. -
status- a symbol column such that:status=yeswhenactiveis1bstatus=nowhenactiveis0b
Example output:
sym px qty active status
------------------------------
cfl 2.296615 8 0 no
bpm 6.919531 1 1 yes
icj 4.707883 9 1 yes
ini 6.346716 5 0 no
nmo 9.672398 4 0 no
ojj 2.306385 6 0 no
bjc 9.49975 6 1 yes
khd 4.39081 1 0 no
hjb 5.759051 8 1 yes
lhk 5.919004 5 1 yesSolution
update active:(count t)?0b from `t
update status:`no`yes active from `tAlternative Solution
update status:?[active;`yes;`no] from update active:(count t)?0b from tThis version returns a new table rather than modifying t.
Note that active must be created before the update that uses it. Within a single update (or select), each column expression sees only the columns of the input table, so writing update active:(count t)?0b, status:`no`yes active from `t fails with 'active.
Explanation
The expression:
(count t)?0bgenerates one random boolean value per row in the table.
For a table containing 10 rows:
count treturns:
10and:
10?0bmight produce:
0110001011bThese values are assigned to the active column.
Mapping Booleans to Symbols
In q, booleans can be used directly as indices.
Consider:
`no`yes 0Result:
`noand:
`no`yes 1Result:
`yesTherefore:
`no`yes activemaps every boolean value to its corresponding symbol.
For example, `no`yes 0110b returns:
`no`yes`yes`noThis is often the most concise way to convert boolean flags into labels.
Alternative Approach
The vector conditional:
?[active;`yes;`no]evaluates:
if active then yes else nofor each row.
While slightly more verbose, it can be easier to read when the logic becomes more complex.
Summary
This question demonstrates two useful techniques:
- Generating random data using
? - Using boolean values as list indices
The expression:
`no`yes activeis a common q idiom for mapping booleans directly to descriptive labels.