table

Methods

Method Reference: table.groupfilter

table: G = groupfilter (T, groupvars, method)
table: G = groupfilter (T, groupvars, groupbins, method)
table: G = groupfilter (…, method, datavars)

Filter the rows of a table by a per-group condition.

G = groupfilter (T, groupvars, method) groups the rows of the table T by the grouping variables groupvars, applies the filter function method to each group, and returns the table G holding the rows that satisfy the condition, in their original order and with all the variables of T. groupvars selects the grouping variables by name, index, logical vector, function handle, or vartype subscript.

method is a function handle applied to each group’s slice of every data variable. It must return either a logical scalar, which keeps or drops the whole group, or a logical vector with one element per row of the group, which keeps or drops the individual rows. A row is kept only when the condition holds for it across all data variables.

G = groupfilter (T, groupvars, method, datavars) applies method only to the data variables selected by datavars (named, indexed, logical, function handle, or vartype subscript). By default every variable that is not a grouping variable is a data variable.

Rows holding a missing value in a grouping variable form their own groups, to which method is applied like any other group.

The optional groupbins argument bins the grouping variables before grouping, using bin edges, a number of equal-width bins, a duration bin width, or a datetime calendar-unit keyword, or a cell array with one scheme per grouping variable; see groupsummary for details. The 'IncludedEdge' Name-Value pair ('left' by default, or 'right') selects which bin edge is inclusive.

Source Code: table

Example: 1

groupfilter keeps the rows belonging to groups that satisfy a predicate — it filters whole groups, not individual rows. Here only species with more than two observations are retained.

 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
 groupfilter (T, 'Species', @(x) numel (x) > 2)
ans =
  3x2 table

     Species      Petal    
    __________    _____    

    {'setosa'}      1.4    
    {'setosa'}      1.5    
    {'setosa'}      1.3

setosa has three rows and stays; virginica has two and is dropped entirely.