Tutorials/Tables I/Solutions

From Kx Wiki
Jump to: navigation, search

1. Make an unkeyed table with 3 columns: one for the days of the week (as symbols), one for the temperature (integers) and the last with a string describing the weather e.g. "cloudy".

q)w:([]day:`Mo`Tu`We`Th`Fr`Sa`Su;temp:22 23 21 19 17 19 24;cond:("cloudy";"sunny
";"rain";"haze";"storm";"fine";"clear"))
q)w
day temp cond
-----------------
Mo  22   "cloudy"
Tu  23   "sunny"
We  21   "rain"
Th  19   "haze"
Fr  17   "storm"
Sa  19   "fine"
Su  24   "clear"

2. Key your table on the day column.

q)w:1!w
q)w
day| temp cond
---| -------------
Mo | 22   "cloudy"
Tu | 23   "sunny"
We | 21   "rain"
Th | 19   "haze"
Fr | 17   "storm"
Sa | 19   "fine"
Su | 24   "clear"

3. Add a row to your (keyed) table with a fictitious eighth day of the week.

q)`w insert (`Mi;24;"stormy")
,7
q)w
day| temp cond
---| -------------
Mo | 22   "cloudy"
Tu | 23   "sunny"
We | 21   "rain"
Th | 19   "haze"
Fr | 17   "storm"
Sa | 19   "fine"
Su | 24   "clear"
Mi | 24   "stormy"

4. Replace the entry for Monday with a temperature of 1000 and the description "appallingly wet".

q)`w upsert (`Mo;1000;"appallingly wet")
`w
q)w
day| temp cond
---| ----------------------
Mo | 1000 "appallingly wet"
Tu | 23   "sunny"
We | 21   "rain"
Th | 19   "haze"
Fr | 17   "storm"
Sa | 19   "fine"
Su | 24   "clear"
Mi | 24   "stormy"

One can also replace using the key as an index. Here's the record for Tuesday:

q)w[`Tu]
temp| 23
cond| "sunny"

The record looks like a dictionary. Indeed, one can insert a dictionary here:

q)w[`Tu]:`cond`temp!("far too hot";42)
q)w
day| temp cond
---| ----------------------
Mo | 1000 "appallingly wet"
Tu | 42   "far too hot"
We | 21   "rain"
Th | 19   "haze"
Fr | 17   "storm"
Sa | 19   "fine"
Su | 24   "clear"
Mi | 24   "stormy"
q)

Or more simply, by following the order of the columns:

q)w[`We]:(36;"still too hot")
q)w
day| temp cond
---| ----------------------
Mo | 1000 "appallingly wet"
Tu | 42   "far too hot"
We | 36   "still too hot"
Th | 19   "haze"
Fr | 17   "storm"
Sa | 19   "fine"
Su | 24   "clear"
Mi | 24   "stormy"
Personal tools
Namespaces
Variants
Actions
Navigation
Print/export
Toolbox