Grouping and Aggregation

A grouping is a collection of keys and sets of indexes into a dataset. Each element of the grouping corresponds to a subset (i.e. a group of observations) of a dataset. Groups may overlap. Moving windows and partitions are examples of groupings.

A grouping is most commonly used in combination with one or more aggregators. An aggregator is a function that reduces one or more vectors to a single value, like the sum or the mean of the elements or the correlation between two vectors. Using an aggregator in combination with a grouping on a data frame, matrix or vector results in a new data frame, matrix or vector with the aggregator applied to each group. The grouping's index becomes the (row) index of the resulting collection. Aggregators can also be used without groupings to reduce an entire data frame, matrix or vector to a single vector or value.

For dataframe work, the modern aggregation workflow uses immutable aggregation descriptors. Descriptor-based dataframe aggregation wraps the existing AggregatorGroup and BinaryAggregatorGroup primitives in user-facing requests that select columns, name outputs, and bind to a data frame. See Aggregating data frames for descriptor examples.

Quantile default names distinguish Q1, Median, Q3, and arbitrary percentiles such as q95. Combining first quartile, median, and third quartile aggregators for Age produces the column keys (Age, Q1), (Age, Median), and (Age, Q3). Quantile definitions other than the default append _type_N using the R type number. The overload that accepts field/aggregator pairs and an explicit output index uses the supplied keys unchanged. Explicit aliases on Aggregation<C, COut> descriptors also take priority over generated names.

Repeated final aggregation output keys are rejected before aggregation. This includes requesting the same quantile twice for the same field or supplying duplicate explicit aliases. Choose distinct output keys using the explicit-index overload or descriptor aliases. The same statistic name on different fields is valid.

A categorical vector used through IGrouping retains its declared category index, category order, and unobserved categories. As<TKey>() returns a typed grouping over the existing membership array. Its key type must match the category key type exactly; incompatible requests throw InvalidCastException. Unassigned rows are excluded. Empty groups retain the aggregator's normal behavior: Count returns zero and Mean returns a missing value. Categorical-vector overloads of DataFrame<R, C> select these semantics directly, both when the key type is inferred and when it is supplied explicitly. This applies to aggregators over all columns and to selected field/aggregator pairs. Passing an IGrouping explicitly selects the same grouping path.

In this section: