stack

Stacks several table variables into a single variable (wide to long).

Category: Language Fundamentals > Data Types

Syntax

S = stack(U, vars)

Stacks the variables vars into one data variable, with an indicator variable naming the source.

S = stack(___, 'NewDataVariableName', n, 'IndexVariableName', m)

Names the new data and indicator variables.

Description

Wide data keep one measurement per column (Q1, Q2, Q3); long data keep one measurement per row, with a column telling which one it is. Many grouping and plotting functions want the long form. The default names join the stacked variable names, as in Q1_Q2_Q3. unstack goes back to the wide form.

Input arguments

U
Table.
vars
Names or indices of the variables to stack.
'NewDataVariableName'
Name of the combined data variable.
'IndexVariableName'
Name of the indicator variable.

Output arguments

S
Table with height(U) * numel(vars) rows: rows of U come one after another, each repeated once per stacked variable.

Example

T = table([1;2], [3;4], [5;6], 'VariableNames', {'Q1','Q2','Q3'});
stack(T, {'Q1','Q2','Q3'}, 'NewDataVariableName', 'Val', 'IndexVariableName', 'Q')
Output
ans = 6×2 table

    Q     Val
    __    ___

    Q1     1 
    Q2     3 
    Q3     5 
    Q1     2 
    Q2     4 
    Q3     6

See also

unstack pivot splitvars mergevars table rows2vars