take

Syntax

take(X, n)

Details

  • If X is a scalar (n must also be a scalar): Generates a vector containing n identical values of X.

  • If X is a vector or a tuple:

    • if n is a scalar: takes n elements from X sequentially. It can be left to right (if n > 0) or right to left (if n < 0). The result is a vector.

    • if n is a vector (must be of the same length as X): takes n[i] copies of X[i]. If n[i] <= 0, it skips X[i]. The result is a vector.

  • If X is a matrix or table:

    • if n is a scalar: It takes n rows of X sequentially, either from top to bottom (if n > 0) or bottom to top (if n < 0). The result is a matrix or table.

    • if n is a vector (must be of the same length as the number of rows in X): takes n[i] copies of the element at the i-th row of X. If n[i] <= 0, it skips the i-th row and takes no elements. The result is a matrix or table.

Note:

DolphinDB take and numpy.take are both used for value retrieval. The differences are as follows:

  • DolphinDB take retrieves a specified number of elements or rows sequentially from a scalar, vector, matrix, or table. If the requested number exceeds the length of the original object, values are taken cyclically. When n is a vector, it specifies the repetition count for each element or row.

  • numpy.take extracts elements from an array according to indices. Its second parameter, indices, specifies index positions rather than the number of values to retrieve, and it also supports the axis and mode parameters.

Parameters

X is a scalar/vector/tuple/matrix/table.

n is an integer or a vector of integers.

Examples

take(10,5);
// output: [10,10,10,10,10]

x=`IBM`C`AAPL`BABA;
take(x,10);
// output: ["IBM","C","AAPL","BABA","IBM","C","AAPL","BABA","IBM","C"]
// sequentially and iteratively take 10 elements from vector x

x=3 5 4 6 9;
take(x,3);
// output: [3,5,4]


x=1..3;
x.take(10);
// output: [1,2,3,1,2,3,1,2,3,1]

take(1 2 3, 10);
// output: [1,2,3,1,2,3,1,2,3,1]


take(1,10);
// output: [1,1,1,1,1,1,1,1,1,1]
// an efficient way to generate a vector with default values.


x=take(1,0);
// return an empty INT VECTOR

x;
// output: []

typestr x;
// output: FAST INT VECTOR
x=1..12$3:4;
take(x,2);
col1 col2 col3 col4
1 4 7 10
2 5 8 11
take(x,-2);
col1 col2 col3 col4
2 5 8 11
3 6 9 12
take(1..3,2 0 2)
// output
[1,1,3,3]
m=matrix(1 2 3, 4 5 6)
take(m,5)
col1 col2
1 4
2 5
3 6
1 4
2 5
take(m, 0 2 1)
col1 col2
2 5
2 5
3 6
t=table(1 2 3 as a, 4 5 6 as b)
take(t,-4)
a b
3 6
1 4
2 5
3 6
take(t, -2 2 1)
a b
2 5
2 5
3 6