pivot
Summarizes a table into a pivot table, with grouped rows and columns.
Category: Language Fundamentals > Data Types
Syntax
P = pivot(T, Rows=r, Columns=c, DataVariable=v)
Groups by the row and column variables and aggregates v in each cell.
P = pivot(___, Method=m)
Chooses the aggregation, for example "sum" or "mean".
Description
A pivot table cross-tabulates a long table. In the example, R gives the rows, C gives the columns and the entries of V are added in each cell. If you leave out Columns, the result has one aggregated column, named after the method and the data variable, such as mean_V.
Input arguments
T- Input table.
Rows- Variable(s) whose values label the output rows.
Columns- Variable whose values become output columns.
DataVariable- Variable to aggregate.
Method- Aggregation method such as
"sum","mean"or"count".
Output arguments
P- Table with one row per distinct row value and one column per distinct column value. Empty combinations hold
0.
Example
T = table(["a";"b";"a";"b"], [1;1;2;2], [10;20;30;40], 'VariableNames', {'R','C','V'});
pivot(T, Rows="R", Columns="C", DataVariable="V", Method="sum")
pivot(T, Rows="R", DataVariable="V", Method="mean")
Output
ans = 2×3 table
R 1 2
___ __ __
"a" 10 30
"b" 20 40
ans = 2×2 table
R mean_V
___ ______
"a" 20
"b" 30