table

Methods

Method Reference: table.splitapply

table: Y = splitapply (func, T, G)
table: [Y1, …, YM] = splitapply (func, T, G)

Split table data into groups and apply a function to each group.

Y = splitapply (func, T, G) splits the rows of the table T into groups according to the group numbers G (typically produced by findgroups), applies the function handle func to each group, and concatenates the per-group results into the output Y. G must be a column vector of positive integers with one element per row of T; if it identifies N groups, every integer between 1 and N must occur at least once. Rows for which G is NaN are omitted. Each variable of T is passed to func as a separate input argument, so func must accept as many arguments as T has variables.

[Y1, …, YM] = splitapply (…) returns the multiple outputs of func, each concatenated across groups.

Source Code: table

Example: 1

splitapply divides a table by the group numbers from findgroups, applies a function to each group, and concatenates the results. Here it computes a mean petal length per species.

 Species = {'setosa'; 'virginica'; 'setosa'; 'virginica'; 'setosa'};
 Petal = [1.4; 5.1; 1.5; 5.9; 1.3];
 T = table (Species, Petal)
T =
  5x2 table

       Species       Petal    
    _____________    _____    

    {'setosa'   }      1.4    
    {'virginica'}      5.1    
    {'setosa'   }      1.5    
    {'virginica'}      5.9    
    {'setosa'   }      1.3
 G = findgroups (T(:, 'Species'));
 splitapply (@mean, T(:, 'Petal'), G)
ans =

   1.4000
   5.5000

The applied function may return several outputs — one column each — and can read several variables at once.

 [lo, hi] = splitapply (@(x) deal (min (x), max (x)), T(:, 'Petal'), G);
 [lo, hi]
ans =

   1.3000   1.5000
   5.1000   5.9000