segment

Syntax

segment(X, [segmentOffset=true])

Arguments

X is a vector.

segmentOffset (optional) is a Boolean value. The default value is true.

Details

Divide a vector into groups. Each group is composed of identical values next to each other. For example, [1,1,2,2,1,1,1] is divided into 3 groups: [1,1], [2,2] and [1,1,1].

Return a vector of the same length as X.

  • If segmentOffset=true, each element of the result is the index(in X) of the first element in each group.
  • If segmentOffset=false, each element of the result is its group number. Group numbers start from 0.

Examples

Example 1.

x = 1 1 2 4 4 5 2 5 NULL NULL
segment(x);
// output
[0,0,2,3,3,5,6,7,8,8]

segment(x, false);
// output
[0,0,1,2,2,3,4,5,6,6]

Example 2.

x = 1 2 1 2 1 2 1 2 1 2 1 2;
y = 0 0 1 1 1 2 2 1 1 3 3 2;
t = table(x,y);
select *, cumsum(x) from t context by segment(y);
y x cumsum_x
0 1 1
0 2 3
1 1 1
1 2 3
1 1 4
2 2 2
2 1 3
1 2 2
1 1 3
3 2 2
3 1 3
2 2 2