# Using Weighted Averages

Canonical page: https://www.adaptabletools.com/docs/handbook-aggregation-weighted-average

- AdapTable offers 2 ways to provide Weighted Averages:
  
  - through Weighted Average Aggregations in a [Layout](https://www.adaptabletools.com/docs/handbook-layouts/index.md) (referencing the Weighted Column)
  - via the `AVG` [AdapTableQL Expression Function](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions/index.md) which takes an optional `WEIGHT` parameter
  
- Additionally Weighted Average aggregations can be viewed in [Cell Summary Operations](https://www.adaptabletools.com/docs/handbook-summarising/index.md)

Weighted Averages are a specialised form of aggregation.

They provide a more 'accurate' average of a data set than simply using the arithmetic mean.

As defined by [Investopedia](https://www.investopedia.com/terms/w/weightedaverage.asp):

<i>Weighted average is a calculation that takes into account the varying degrees of importance of the numbers in a data set. In calculating a weighted average, each number in the data set is multiplied by a predetermined weight before the final calculation is made.</i>

- Weighted Averages are commonly used in finance e.g. for statistical analysis or stock portfolios
- But they can be used elsewhwere, for example for teacher grading averages

AdapTable provides 3 different ways of viewing Weighted Averages:

- Creating a Weighted Average **Aggregation** in a [Layout](https://www.adaptabletools.com/docs/handbook-layouts/index.md)
- Seeing the Weighted Average **Summary** in the [Cell Summary](https://www.adaptabletools.com/docs/handbook-summarising/index.md) or [Row Summary](https://www.adaptabletools.com/docs/handbook-summarising-rows/index.md)
- Providing a Weighted Average **Calculation** in an [AdapTableQL Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md)

## Weighted Average Aggregations

In AdapTable Columns can be defined as having Weighted Average Aggregations.

These definitions can be provided by both developers at design-time and end users at run-time.

Each [Layout](https://www.adaptabletools.com/docs/handbook-layouts/index.md) in AdapTable contains a `TableAggregationColumns` (or `PivotAggregationColumns`) property.

This defines which Columns to aggregate, and which operation to use, when the Grid is Row-Grouped.

Guides for Defining [Table Layouts](https://www.adaptabletools.com/docs/handbook-layouts-table/index.md) and [Pivot Layouts](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md) explain in detail how to provide Aggregations

The `TableAggregationColumns` (or `PivotAggregationColumns`) property can also be of type _WeightedAverageAggregation_.

Adaptable provides a custom aggFunc of `weightedAverage` which is added to the aggFuncs supplied by AG Grid

This object is a record where the key is the name of the Column which will be Aggregated, and a `weightedColumnId` property supplies the name of the column providing the Weight.

There is also a `type` property which should always be set to 'weightedAverage'

So imagine a scenario where you have a Grid with an `examResult` column but you want to provide a weighted average using another column, `attendance` in the calculation.

The Initial Adaptable State to create the Weighted Average would be:

```ts
TableAggregationColumns: [
  {
    ColumnId: 'examResult',
    AggFunc: {
      type: 'weightedAverage',
      weightedColumnId: 'attendance',
    },
  },
],
```

- It is also possible to create a Weighted Average aggregation using the [Table Layout Wizard](https://www.adaptabletools.com/docs/handbook-layouts-wizard-table/index.md)
- When `weightedAvg` is the selected *aggFunc*, AdapTable will display a second dropdown for the Weighted Column

### Column Menu

AdapTable also allows you to set the Weighted Average aggregation from the [Column Menu](https://www.adaptabletools.com/docs/ui-column-menu/index.md).

The menu item only appears when the grid is **row grouped** (same as AG Grid's *Value Aggregation* menu)

Configuring the aggregation via the Column Menu is a 2-step process:

- choose `Weighted Average` from the `Value Aggregation` menu item in the Column Menu in the column which you want to aggregate (`weightedAvg` must be included in the column's effective `allowedAggFuncs`)

- pick the weight column from the submenu which appears that lists every numeric column in the Grid

- The aggregation displays in column header as `weightedAvg(ValueColumn-WeightColumn)`
- e.g. a weighted average on Exam Result / Attendance produces `weightedAvg(Exam Result-Attendance)`
- Set `SuppressAggFuncInHeader` to *true* to display only the column name (same as for other aggregations)

### Filtering

The Weighted Average Aggregation evaluates using only the **currently filtered rows** in the Grid.

This follows the AG Grid pattern where aggregations take filters into account by default unless explicity configured otherwise via the `suppressAggFilteredOnly` property in Grid Options.

Set `suppressAggFilteredOnly` to *true* in Grid Options for Weighted Average aggregations to include non-filtered rows

### Hiding Weighted Average

It is possible to hide the `weightedAverage` aggregation if this is not required or useful to your users.

This is done the same way as hiding AG Grid's aggFuncs - via the `allowedAggFuncs` in each ColumnDef.

Hide `weightedAvg` aggFunc by omitting it from list of Column's aggFuncs, e.g. `allowedAggFuncs: ['sum', 'min'],` 

## Weighted Average Summaries

AdapTable is able to display the Weighted Average for any selected Cells or Rows:

- For [Cell Summary](https://www.adaptabletools.com/docs/handbook-summarising-cells/index.md) - select `weightedAvg` in the Cell Summary [Toolbars](https://www.adaptabletools.com/docs/ui-dashboard/index.md#tabs-and-toolbars), [Tool Panel](https://www.adaptabletools.com/docs/ui-tool-panel/index.md) or [Status Panel](https://www.adaptabletools.com/docs/ui-status-bar/index.md)
- For [Row Summary](https://www.adaptabletools.com/docs/handbook-summarising-rows/index.md) - add to the `RowSummaries` property in the Layout

- Cell and Row Summaries require the summarised Column to have an associated [Weighted Average Aggregation](#weighted-average-aggregations)
- This should be provided in the Layout's Aggregations (see above)

## Weighted Averages in Expressions

Weighted Averages can also provided in [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) by using [Aggregation Expressions](https://www.adaptabletools.com/docs/adaptable-ql-expression-aggregation/index.md).

This is particularly useful if you wish to show Weighted Averages in a [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md)

It is achieved by providing a `WEIGHT` parameter to the `AVG` Expression Function.

The `WEIGHT` Expression Function recieves a single argument which is the name of the Column to use for weighting

```ts [[1, 2, "AVG"], [2, 2, "WEIGHT"]]
// Return Weighted Average for 'examResult' Column (using 'attendance' column for weighting)
AVG{[examResult], WEIGHT([attendance])};
```

The Weighting can also be grouped if necessary by using the `GROUP_BY` clause:

```ts [[1, 2, "AVG"], [2, 2, "WEIGHT"], [3, 2, "GROUP_BY"]]
 // Weighted Average for 'examResult' (with 'attendance' for weighting) grouping by Class & Pupil
 AVG{[examResult], WEIGHT([attendance]), GROUP_BY([class], [pupil])}
```

**Example: Using Weighted Averages**

Providing Weighted Average Aggregations

- This example illustrates the different ways that Weighted Averages can be used in AdapTable:
  - **Aggregation** - the `Exam Result` Column has been given a Weighted Average Aggregation, using the `Attendance` Column as the _weighted_ column
  - **Expression Functions**: - the `Calc Column` [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) - has an [Aggregation Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression-aggregation/index.md) (which includes `AVG` with `WEIGHT` and `GROUP_BY` clauses)
  - **Cell Summary** - a [Cell Summary](https://www.adaptabletools.com/docs/handbook-summarising-cells/index.md) has been set to be `Weighted Avg` (and some cells have been highlighted for convenience)
  - **Row Summary** - a [Row Summary](https://www.adaptabletools.com/docs/handbook-summarising-rows/index.md) has been added to the top of the Grid showing Weighted Average for `Exam Result` Column
- Note: the Calculated Column provides the same result as the Weighted Average Aggregation and Selected Cells Summary

### Expand to see how these 3 Weighted Average elements were set up

The Weighted Average Aggregation for the `Exam Result` Column was provided in Layout Initial State

```ts
Layout: {
  CurrentLayout: 'Full Layout',
  Layouts: [
    {
      Name: 'Full Layout',
      TableColumns: ['pupil', 'subject','examResult', 'attendance', 'class', 'Calc'],
      RowGroupedColumns: ['class', 'pupil'],
      SuppressAggFuncInHeader: true,
      TableAggregationColumns: [
      {
        ColumnId: 'examResult',
        AggFunc: {
          type: 'weightedAverage',
          weightedColumnId: 'attendance',
        },
      }],
    },
  ],
},
```

The [Cell Summary](https://www.adaptabletools.com/docs/handbook-summarising/index.md) Operation was set to `Weighted Avg`, row groups opened and cells highlighted using [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md) methods:

```ts
adaptableApi.cellSummaryApi.setCurrentCellSummaryOperation('Weighted Avg');
adaptableApi.gridApi.expandAllRowGroups();
setTimeout(() => {
  const gridCellRange: GridCellRange = {
    columnIds: ['examResult'],
    rowIndexStart: 2,
    rowIndexEnd: 4,
  };
  adaptableApi.gridApi.selectCellRange(gridCellRange);
}, 100);
```

The `Calc Column` [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) was defined in Calculated Column Initial State:

```ts
CalculatedColumn: {
  CalculatedColumns: [
  {
    ColumnId: 'calcColumn',
    FriendlyName: 'Calc Column',
    Expression: 'AVG{[examResult], GROUP_BY([class], [pupil]), WEIGHT([attendance])}',
    CalculatedColumnSettings: {
      DataType: 'number',
    },
  },
]},
```

- Select the 5 cells for Andy in the `Exam Result` column and not how all the Aggregations add up
- Type 2 in the filter for the `Attendance` column (to filter the Grid) and not how the Exam Result aggregations automatically change

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'Id',
  adaptableId: 'Weighted Average',
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Main',
          Toolbars: ['CellSummary', 'Layout'],
        },
      ],
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['CellSummary', 'Layout'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'calcColumn',
          FriendlyName: 'Calc Column',
          Expression: 'AVG{[examResult], GROUP_BY([class], [pupil]), WEIGHT([attendance])}',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Full Layout',
      Layouts: [
        {
          Name: 'Full Layout',
          TableColumns: [
            'pupil',
            'subject',
            'examResult',
            'attendance',
            'class',
            'calcColumn',
          ],
          RowGroupedColumns: ['class', 'pupil'],
          RowSummaries: [
            {
              Position: 'Top',
              ColumnsMap: {
                examResult: 'WEIGHTED_AVERAGE',
              },
            },
          ],
          SuppressAggFuncInHeader: true,
          TableAggregationColumns: [
            {
              ColumnId: 'examResult',
              AggFunc: {
                type: 'weightedAverage',
                weightedColumnId: 'attendance',
              },
            },
            {
              ColumnId: 'blah',
              AggFunc: true,
            },
          ],
          AutoSizeColumns: true,
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-examResult',
          Scope: {
            ColumnIds: ['examResult', 'calcColumn'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 2,
            },
          },
        },
      ],
    },
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    headerName: 'Id',
    field: 'resultId',
    hide: true,
    cellDataType: 'number',
  },
  {
    headerName: 'Subject',
    field: 'subject',
    editable: true,
    cellDataType: 'text',
    enableRowGroup: true,
    sortable: true,
    filter: true,
    resizable: true,
  },
  {
    headerName: 'Pupil',
    field: 'pupil',
    editable: true,
    cellDataType: 'text',
    enableRowGroup: true,
    sortable: true,
    filter: true,
    resizable: true,
  },
  {
    headerName: 'Exam Result',
    field: 'examResult',
    editable: true,
    cellDataType: 'number',
    sortable: true,
    aggFunc: 'sum',
    enableValue: true,
    filter: true,
    resizable: true,
  },
  {
    headerName: 'Attendance',
    field: 'attendance',
    editable: true,
    enableValue: true,
    cellDataType: 'number',
    sortable: true,
    filter: true,
    resizable: true,
  },
  {
    headerName: 'Class',
    field: 'class',
    editable: true,
    enableRowGroup: true,
    enableValue: true,
    cellDataType: 'text',
    sortable: true,
    filter: true,
    resizable: true,
  },
];
```

**`src/rowData.ts`**

```ts
export const rowData = [
  {
    resultId: 1,
    pupil: 'Tim',
    subject: 'Maths',
    examResult: 40,
    attendance: 3,
    class: 'Year 7',
  },
  {
    resultId: 2,
    pupil: 'Tim',
    subject: 'English',
    examResult: 30,
    attendance: 2,
    class: 'Year 7',
  },
  {
    resultId: 3,
    pupil: 'Tim',
    subject: 'French',
    examResult: 30,
    attendance: 5,
    class: 'Year 7',
  },
  {
    resultId: 4,
    pupil: 'Andy',
    subject: 'Maths',
    examResult: 20,
    attendance: 2,
    class: 'Year 7',
  },
  {
    resultId: 5,
    pupil: 'Andy',
    subject: 'History',
    examResult: 20,
    attendance: 2,
    class: 'Year 7',
  },
  {
    resultId: 6,
    pupil: 'Andy',
    subject: 'French',
    examResult: 20,
    attendance: 3,
    class: 'Year 7',
  },
  {
    resultId: 7,
    pupil: 'Andy',
    subject: 'English',
    examResult: 10,
    attendance: 3,
    class: 'Year 7',
  },
  {
    resultId: 8,
    pupil: 'Andy',
    subject: 'Physics',
    examResult: 30,
    attendance: 5,
    class: 'Year 7',
  },
  {
    resultId: 9,
    pupil: 'Sally',
    subject: 'English',
    examResult: 20,
    attendance: 3,
    class: 'Year 8',
  },
  {
    resultId: 10,
    pupil: 'Sally',
    subject: 'Physics',
    examResult: 20,
    attendance: 5,
    class: 'Year 8',
  },
  {
    resultId: 11,
    pupil: 'Mark',
    subject: 'English',
    examResult: 10,
    attendance: 3,
    class: 'Year 8',
  },
  {
    resultId: 12,
    pupil: 'Mark',
    subject: 'Physics',
    examResult: 10,
    attendance: 5,
    class: 'Year 8',
  },
  {
    resultId: 13,
    pupil: 'Mark',
    subject: 'Physics',
    examResult: 25,
    attendance: 5,
    class: 'Year 8',
  },
];
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {rowData} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  rowGroupPanelShow: 'always',
  grandTotalRow: 'bottom',
  statusBar: {
    statusPanels: [
      {
        key: 'Left Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'left',
      },
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
      {
        key: 'Right Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'right',
      },
    ],
  },
  suppressMenuHide: true,
  cellSelection: true,
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo, GridCellRange} from '@adaptabletools/adaptable';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  adaptableApi.cellSummaryApi.setCurrentCellSummaryOperation('Weighted Avg');
  adaptableApi.gridApi.expandAllRowGroups();
  setTimeout(() => {
    const gridCellRange: GridCellRange = {
      columnIds: ['examResult'],
      rowIndexStart: 2,
      rowIndexEnd: 4,
    };
    adaptableApi.gridApi.selectCellRange(gridCellRange);
  }, 100);
};
```

### FAQ

**What happened to Weighted Averages in Finance Plugin?**
These were removed in [Version 12](https://www.adaptabletools.com/support/version-12-release-note) and replaced by the superior options offered here

**Why does the Weighted Average Aggregtion evaluate all rows, and not just filtered ones?**
This will be fixed in a future patch, and AG Grid's `suppressAggFilteredOnly` property will be used when deciding which rows should be included in the evaluation
