grouptransform

Transforms table data group by group, keeping the original row layout.

Category: Language Fundamentals > Data Types

Syntax

B = grouptransform(T, groupvars, method)

Replaces the data variables by the transformed values.

B = grouptransform(T, groupvars, method, datavars)

Transforms only the listed variables.

Description

Unlike groupsummary, which collapses each group to one row, grouptransform returns a value for every original row. Typical uses are centering by group (@(x) x - mean(x)) or normalizing within each group.

Input arguments

T
Table.
groupvars
Variable(s) that define the groups.
method
Function handle applied to the values of each group. It returns a vector of the same length, or a scalar that is repeated for the group.
datavars
Variable(s) to transform.

Output arguments

B
Table with the same number of rows and order as T.

Example

Centering by group

tb = table(categorical({'a'; 'b'; 'a'; 'c'; 'a'}), [1; 2; 3; 4; 5], 'VariableNames', {'g', 'v'});
grouptransform(tb, 'g', @(x) x - mean(x), 'v')
Output
ans = 5×2 table

    g    v 
    _    __

    a    -2
    b     0
    a     0
    c     0
    a     2

See also

groupsummary groupfilter groupcounts findgroups splitapply