How can I find the data type of a given table column?

Short answer: meta tablename

For example –

q)\l sp.q        / found in $QHOME/sp.q
q)s
s | name  status city
--| -------------------
s1| smith 20     london
s2| jones 10     paris
s3| blake 30     paris
s4| clark 20     london
s5| adams 30     athens
q)meta s
c     | t f a
------| -----
s     | s
name  | s
status| i
city  | s
q)

The output of meta is a kdb table, where columns c and t indicate the column name and data type, respectively.

The key the provides an alternate method:

q)key exec city from s
`symbol
q)

If you need the type code, use the type function:

q)type exec city from s
11h
q)

See also: Type character definitions, Meta output faq.

How can I test for the existence of a file or directory in q?

Short answer: key file_handle or key dir_handle

File handle example:

q)\touch /tmp/test.txt q)key hsym ` $ "/tmp/test.txt" `:/tmp/test.txt q)

The function key returns an empty list when the file does not exist:

q)hdel `:/tmp/test.txt `:/tmp/test.txt q)() ~ key `:/tmp/test.txt 1b q)

key is one of the most heavily overloaded functions in q. It accepts an argument of type dictionary, keyed table, table column, list, and integer. It’s easy to confuse it with keys, which turns out to be an entirely different function.

See also: ~ (match), \ (system), hdel, hsym

How can I slice a vector into a series of vectors of length n?

By passing the # (take) operator a pair as its first (i.e., left) argument:

q)2 5 # til 10
0 1 2 3 4
5 6 7 8 9

When # is used in this way, it is referred to as “reshape.” We like to call this, “taking a box.” Just like when you apply # with an integer left argument, taking a box stops when you have taken as many items as requested, leaving the rest behind:

q)3 3 # til 10
0 1 2
3 4 5
6 7 8

Similarly, when you over-take a box, you start over from the beginning of the source:

q)4 3 # til 10
0 1 2
3 4 5
6 7 8
9 0 1

If you want to take all the items from the source, pass 0N as the first element of the box:

q)0N 2 # til 10
0 1
2 3
4 5
6 7
8 9

If you take a whole box, but the elements from the source don’t fit, you end up with a short list in the last row:

q)0N 3 # til 10
0 1 2
3 4 5
6 7 8
,9
q)

See also: cut and faq on _ (drop)


This work is licensed under a Creative Commons License.
The views and opinions expressed herein are those of the authors and do not necessarily reflect those of any other person or legal entity.
Kdb+ is the registered trademark of Kx Systems, Inc.