groupfilter
Keeps only the rows of groups that satisfy a condition.
Category: Language Fundamentals > Data Types
Syntax
B = groupfilter(T, groupvars, fun)
Applies fun to the data of each group and keeps the groups for which it returns true.
B = groupfilter(T, groupvars, fun, datavars)
Passes only the listed data variables to fun.
Description
This is a filter at the group level. For example, groupfilter(T, 'g', @(x) numel(x) > 1, 'v') drops every group that has a single row. The test sees the whole group at once, which is what separates it from logical indexing on single rows.
Input arguments
T- Table.
groupvars- Variable(s) that define the groups.
fun- Function handle receiving the group's values and returning a logical scalar, or a logical vector with one entry per row.
datavars- Variable(s) given to
fun.
Output arguments
B- Table with the rows of the groups that passed, in original order.
Example
Dropping small groups
tb = table(categorical({'a'; 'b'; 'a'; 'c'; 'a'}), [1; 2; 3; 4; 5], 'VariableNames', {'g', 'v'});
groupfilter(tb, 'g', @(x) numel(x) > 1, 'v')
Output
ans = 3×2 table
g v
_ _
a 1
a 3
a 5
See also
groupsummary grouptransform groupcounts findgroups splitapply