« How can I group all (other) columns? | Main | Can I retrieve kdb data from my web browser and save the query results to a csv file for viewing in a spreadsheet? »

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)

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Textile formatting is allowed.