# Calculated Columns

Canonical page: https://www.adaptabletools.com/docs/handbook-calculated-column

- Calculated Columns are _special_ columns which display a _calculated_ value
- Unlike _regular_ columns, Calculated Columns do not display data from AG Grid's data source
- Instead, the displayed values are derived _(calculated)_ from other columns
- The calculation takes the form of an AdapTableQL Expression
- This is evaluated and kept in sync with the live data
- The Expression always returns a single value and can be (depending on the complexity required):
  - `Standard` - value returned is based on other cells in the row
  - `Observable` - value returned from change history (and time)
  - `Aggregated` - value returned is based on other rows in the Grid 
  - `Cumulative` - uses an Aggregation operation applied cumulatively to rows in specific order 
  - `Quantile` -  value is derived from other rows using quantile aggregation 
  - `Window` -  looks up values from other rows in an ordered series 
- Once created a Calculated Column can be used and managed like any other Column in AG Grid

- **No new development**: runtime users create new Columns in Expression Editor: no code, releases or back-end work
- **Far more than simple row formulas**: 6 calculation types - aggregations across groups, running totals, quantile buckets, previous / next row lookups, and values based on how data has changed over time
- **Always live**: values recalculate automatically as the underlying data ticks, so the Grid is never out of date
- **First-class Columns**: Calculated Column can be sorted, filtered, grouped, pivoted, formatted, alerted and exported
- **Build on each other**: Can reference other Calculated Columns, so complex logic broken into simple, reusable steps
- **Transparent, Excel-style**: Formula Trace shows users how each value was derived, building trust in the numbers
- **Powerful & extensible**: large library of built-in Expression Functions, plus your Custom Functions where required
- **Lightweight and shareable**: only the definition is stored (never the data), and definitions can be Team Shared
- **Evaluate where it suits you**: let AdapTable evaluate in browser, or you evaluate on your server (with large data)

Calculated Columns are a special type of column which display an **evaluated** value for each cell.

The Calculated Column definition contains an [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) which is evaluated dynamically by [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md).

The Expression is typically a Standard Expression (i.e. it evaluates the cell based on other columns in the row).

But there are more complicated Expression types available for more advanced scenarios including [Aggregated](https://www.adaptabletools.com/docs/handbook-calculated-column-aggregated/index.md), [Cumulative](https://www.adaptabletools.com/docs/handbook-calculated-column-cumulative/index.md), [Quantile](https://www.adaptabletools.com/docs/handbook-calculated-column-quantile/index.md), [Window](https://www.adaptabletools.com/docs/handbook-calculated-column-window/index.md) and [Observable](https://www.adaptabletools.com/docs/handbook-calculated-column-observable/index.md) Calculated Columns.

It is valid for a Calculated Column to display a *static* value, rather than an [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md), though this is a rare use case

Once created, Calculated Columns are treated as regular columns in AdapTable.

These columns do not exist in the underlying AG Grid data source but are still stored with [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md).

- Calculated Columns - like [Free Text Columns](https://www.adaptabletools.com/docs/handbook-freetext-column/index.md) and [Action Columns](https://www.adaptabletools.com/docs/handbook-action-column/index.md) - are not "normal" data columns
- Instead they are **created dynamically** by AdapTable each time the Application runs 
- By contrast [Styled Columns](https://www.adaptabletools.com/docs/handbook-styled-column-overview/index.md) are "normal" data columns, albeit ones which AdapTable specially renders

- AG Grid ships a Calculated Columns feature, which is **different** to AdapTable Calculated Columns
- Do **not** [register](https://www.adaptabletools.com/docs/getting-started-aggrid-modules/index.md) `CalculatedColumnsModule` if you are using AdapTable Calculated Columns
- Importing both gives users two ways to create calculated columns and is likely to cause confusion

## Calculated Column Value

The value displayed in the Calculated Column can be one of 4 types: string, number, date or boolean.

When creating a Calculated Column in the UI, AdapTable will infer the DataType from the Expression result.

- The run-time user can override this inferred result if required
- For Calculated Columns provided via Initial Adaptable State, there is a **mandatory** `DataType` property

### How Calculated Columns Work in AdapTable

Each time the application starts up AdapTable retrieves any Calculated Column definitions from Adaptable State.

For each Calculated Column definition, AdapTable will:

1. Create a [Adaptable Column](https://www.adaptabletools.com/docs/dev-guide-columns-adaptable-column/index.md) with the properties set based on the Definition
2. Either create an equivalent AG Grid column if one is not provided...
3. ...or update an existing AG Grid column (which has a [Column Type](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md#special-columns) of _calculatedColumn_)
4. Create a [ValueGetter](https://www.ag-grid.com/javascript-data-grid/value-getters) for the Column which will invoke the Expression when needed and return the scalar value
5. Keep the Calculated Column value in sync with the referenced column values

## Calculated Column Expressions

Each Calculated Column definition contains an `Expression` property, responsible for providing each cell value.

The Expression is evaluated by [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) for each cell in the column.

- Sometimes developers want to evaluate the Calculated Column themselves, rather than letting AdapTable do it
- To do this, return 'false' for *CalculatedColumn* in the `evaluateAdaptableQLExternally` property in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md)

There are 6 types of Expressions available when using Calculated Columns:

All are *Scalar* meaning the return value can be of **any** type

| Calculation Type                                                                | How Calculated Value is Returned                                            |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| [Standard](https://www.adaptabletools.com/docs/handbook-calculated-column-standard/index.md)      | Based solely on data in the current row                                     |
| [Observable](https://www.adaptabletools.com/docs/handbook-calculated-column-observable/index.md)  | Derived from change history (and time)                                      |
| [Aggregation](https://www.adaptabletools.com/docs/handbook-calculated-column-aggregated/index.md) | Derived from multiple, distinct rows (with optional grouping)               |
| [Cumulative](https://www.adaptabletools.com/docs/handbook-calculated-column-cumulative/index.md)  | Aggregation Operation is applied to each row cumulatively in specific order |
| [Quantile](https://www.adaptabletools.com/docs/handbook-calculated-column-quantile/index.md)      | Aggregated Values are placed into ordered buckets                           |
| [Window](https://www.adaptabletools.com/docs/handbook-calculated-column-window/index.md)          | Look up values from other rows in an ordered series                         |

### Choosing a Calculation Type

| If you need…                                                                          | Read                                                                           |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| A value from other columns in the **same row**                                        | [Standard](https://www.adaptabletools.com/docs/handbook-calculated-column-standard/index.md)     |
| Live stats from **change history** or elapsed time (ticks, session high/low, row age) | [Observable](https://www.adaptabletools.com/docs/handbook-calculated-column-observable/index.md) |
| A summary across **many rows** (totals, averages, group shares)                       | [Aggregated](https://www.adaptabletools.com/docs/handbook-calculated-column-aggregated/index.md) |
| A **running total** (or similar) in a defined row order                               | [Cumulative](https://www.adaptabletools.com/docs/handbook-calculated-column-cumulative/index.md) |
| **Buckets** (deciles, quartiles, etc.) within a group                                 | [Quantile](https://www.adaptabletools.com/docs/handbook-calculated-column-quantile/index.md)     |
| The value from another row in a **sort order** (`LAG`, `LEAD`, rank)                  | [Window](https://www.adaptabletools.com/docs/handbook-calculated-column-window/index.md)         |

- **Observable** columns shine when data **changes** while the Grid is open (ticks, edits, streaming updates)
- Until a watched cell changes, many Observable functions return empty or static values

- For the **previous value after a tick on this row**, use Observable (e.g. `PREVIOUS`)
- For the **previous row in a sorted series**, use Window (e.g. `LAG`)

### How Multi-Row Types Relate

[Aggregated](https://www.adaptabletools.com/docs/handbook-calculated-column-aggregated/index.md) expressions combine values from multiple rows (optionally with `GROUP_BY`). 

[Cumulative](https://www.adaptabletools.com/docs/handbook-calculated-column-cumulative/index.md), [Quantile](https://www.adaptabletools.com/docs/handbook-calculated-column-quantile/index.md), and [Window](https://www.adaptabletools.com/docs/handbook-calculated-column-window/index.md) expressions build on that model:
- cumulative applies an aggregation in order through the grid
- quantile places each row into ordered buckets
- window orders rows and reads from another position in that ordering

**Example: Calculated Columns: Introducing**

Calculated Columns: How they work

- This demo contains 3 (Numeric) Calculated Columns:
  - `Total PRs` — **Standard**: sums the `Open PRs` and `Closed PRs` columns in each row
  - `Issues Open/Total Ratio` — **Standard**: divides open issues by total issues in the row
  - `Sum Pop by Lang` — **Aggregated**: sums `Github Stars` for all rows in the same `Language` (see [Aggregated Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-aggregated/index.md))

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  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';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Basic Calculated Columns',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout', 'CalculatedColumn'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'open_pr_count',
            'closed_pr_count',
            'total_pr_count',
            'open_issues_count',
            'closed_issues_count',
            'open-total-issue-ratio',
            'github_watchers',
            'language',
            'sum-popularity-by-lang',
            'licence',
            'github_stars',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          FriendlyName: 'Total PRs',
          ColumnId: 'total_pr_count',
          Expression: '[open_pr_count] + [closed_pr_count]',
          CalculatedColumnSettings: {
            DataType: 'number',
            Filterable: true,
          },
        },
        {
          FriendlyName: 'Issues Open/Total Ratio',
          ColumnId: 'open-total-issue-ratio',
          Expression: '[open_issues_count] / ([open_issues_count] +[closed_issues_count])',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
        },
        {
          ColumnId: 'sum-popularity-by-lang',
          FriendlyName: 'Sum Pop by Lang',
          Expression: 'SUM{[github_watchers], GROUP_BY([language])}',
          CalculatedColumnSettings: {
            DataType: 'number',
            Groupable: true,
          },
        },
      ],
    },
  },
};
```

## Creating Calculated Columns

Calculated Columns, like most AdapTable Objects, can be created in 2 ways:

- defined at design-time in [Calculated Column Initial Adaptable State](https://www.adaptabletools.com/docs/technical-reference-calculated-column/index.md)
- created at run-time using the [Calculated Column Wizard](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md#using-calculated-columns)

Once created, Calculated Columns are stored in [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md) (like all [Adaptable Objects](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md#adaptable-objects)).

- Only the Calculated Column **Definition** (e.g. Name, Expression, DataType etc) is stored in AdapTable State
- AdapTable does <b>not</b> store any actual cell data

## Formatting Calculated Columns

As stated above Calculated Columns, once created or defined, are treated like any other AdapTable Column.

This means, for example, that they can be used to trigger Alerts, or be included in Reports in Export.

It also allows Calculated Columns to be [fully formatted](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) with Styles, Display Formats and Conditions.

This allows rendering a Calculated Column as a [Sparkline](https://www.adaptabletools.com/docs/handbook-styled-column-sparkline/index.md) (typically by using the `TO_ARRAY` [Expression Function](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions/index.md))

**Example: Calculated Columns: Formatting**

Calculated Columns: Adding Formatting

- This demo contains 5 Calculated Columns each of which has been styled:
- Three Columns have been given [Column Formatting](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md), some with Conditions:
  - `Subscribers Ratio` - has 2 fraction digits and a suffix of '%'
  - `Total PRs` - is right-aligned and italicised.  Also has a Condition to show 'K' (with blue font) where > 1000
  - `Years Old` - has a suffix of "years".  Also has a Condition to show purple with white font where value is > 10
- Two Columns have had a [Styled Column](https://www.adaptabletools.com/docs/handbook-styled-column-overview/index.md) applied:
  - `Big Stars` - has a [Percent Bar Style](https://www.adaptabletools.com/docs/handbook-styled-column-percent-bar/index.md)
  - `Stats` - uses the `TO_ARRAY` function and then renders a [Sparkline Column](https://www.adaptabletools.com/docs/handbook-styled-column-sparkline/index.md)

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template, with charts]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template] + ag-charts-enterprise
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';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Formatting Calculated Columns',
  initialState: {
    Dashboard: {
      ModuleButtons: [
        'CalculatedColumn',
        'FormatColumn',
        'StyledColumn',
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout', 'CalculatedColumn'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'subscribersRatio',
            'licence',
            'total_pr_count',
            'github_stars',
            'yearsOld',
            'bigStars',
            'language',
            'stats',
            'github_watchers',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          FriendlyName: 'Subscribers Ratio',
          ColumnId: 'subscribersRatio',
          Expression: '[github_stars] / [github_watchers]',
          CalculatedColumnSettings: {
            Filterable: true,
            Groupable: true,
            DataType: 'number',
          },
        },
        {
          FriendlyName: 'Total PRs',
          ColumnId: 'total_pr_count',
          Expression: '[open_pr_count] + [closed_pr_count]',
          CalculatedColumnSettings: {
            DataType: 'number',
            Resizable: true,
          },
        },
        {
          FriendlyName: 'Years Old',
          ColumnId: 'yearsOld',
          Expression: 'DIFF_YEARS(CURRENT_DAY(), [created_at])',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
        },
        {
          FriendlyName: 'Big Stars',
          ColumnId: 'bigStars',
          Expression: '[github_watchers] * 5',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
        },
        {
          ColumnId: 'stats',
          FriendlyName: 'Stats',
          Expression: 'TO_ARRAY([closed_pr_count], [closed_pr_count], [open_issues_count], [closed_issues_count])',
          CalculatedColumnSettings: {
            Resizable: true,
            DataType: 'numberArray',
          },
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-subscribersRatio',
          Scope: {
            ColumnIds: ['subscribersRatio'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 2,
              Suffix: '%',
            },
          },
        },
        {
          Name: 'formatColumn-total_pr_count',
          Scope: {
            ColumnIds: ['total_pr_count'],
          },
          Style: {
            FontStyle: 'Italic',
            Alignment: 'Right',
          },
        },
        {
          Name: 'formatColumn-total_pr_count',
          Scope: {
            ColumnIds: ['total_pr_count'],
          },
          Rule: '[total_pr_count] > 1000',
          Style: {
            ForeColor: 'LightBlue',
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              Multiplier: 0.001,
              Suffix: 'K',
            },
          },
        },
        {
          Name: 'formatColumn-yearsOld',
          Scope: {
            ColumnIds: ['yearsOld'],
          },
          Rule: '[yearsOld] > 10',
          Style: {
            BackColor: 'var(--ab-color-palette-28)',
            ForeColor: 'var(--ab-color-palette-14)',
          },
        },

        {
          Name: 'formatColumn-yearsOld',
          Scope: {
            ColumnIds: ['yearsOld'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              Suffix: ' years',
            },
          },
        },
      ],
    },
    StyledColumn: {
      StyledColumns: [
        {
          Name: 'stats Sparkline',
          ColumnId: 'stats',
          SparklineStyle: {
            options: {
              type: 'area',
              fill: 'rgba(216, 204, 235, 0.3)',
              stroke: 'rgb(119,77,185)',
              axis: {
                type: 'category',
                stroke: 'rgb(204, 204, 235)',
              },
            },
          },
        },
        {
          Name: 'bigStars PercentBar',
          ColumnId: 'bigStars',
          PercentBarStyle: {
            RangeValueType: 'Number',
            CellRanges: [
              {
                Min: 'Col-Min',
                Max: 'Col-Max',
                Color: 'green',
              },
            ],
            BackColor: 'var(--ab-color-palette-15)',
          },
        },
      ],
    },
  },
};
```

## Referencing Calculated Columns

A Calculated Column's Expression can reference other Calculated Columns (and regular columns). 

Calculated values can also feed [Charts](https://www.adaptabletools.com/docs/handbook-charts/index.md), [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md), and other modules.

When a referenced column changes, dependent calculated values update too.

See [Referencing Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-referencing/index.md) for chaining, **Formula Trace**, Compact Expression Editor & cross-module use

## Pivoting Calculated Columns

Because Calculated Columns are essentially regular columns, they can also be used in [Pivot Layouts](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md).

They can be referenced in 3 ways when pivoting:

- **Row Group Columns** - AG Grid will display one row for each distinct value in the Calculated Column
- **Pivoted Columns** - AG Grid automatically creates a column for each distinct value in the Calculated Column
- **Aggregation Columns** - AG Grid will display the supplied `aggFunc` (typically `sum` but can be anything)

**Example: Pivoting Calculated Columns**

Using Calculated Columns inside Pivot Layouts

- This Demo contains a [Pivot Layout](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md) with 3 Calculated Columns each used as a different element in a Pivot Layout:
- `Total` (Aggregated Column)
  - adds the values of `Github Stars`and `Github Watchers` columns
  - is used as an **Aggregated Column** in the Layout
  - contains the `sum` aggregation
- `Popularity` (Pivot Column)
  - uses Ternary Logic to say whether the framework is popular (based on the value in `Github Watchers`)
  - Used as a **Pivot Column** in the Layout
  - Note: AG Grid automatically creates one dynamic, pivoted column for each of the 2 distinct Calculated Column values ('Popular', 'Unpopular')
- `Favourites` (Row Grouped Column)
  - uses Ternary Logic to say whether framework is a favourite (i.e. is one of "react", "angular", "vue", "stencil")
  - This is used as a **Row Group** in the Layout
  - Note: AG Grid automatically creates one grouped row for each of the 2 distinct Calculated Column values ('Main', 'Other')

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  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';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Pivoted Calculated Columns',
  initialState: {
    Dashboard: {
      Tabs: [{Name: 'Demo', Toolbars: ['Layout']}],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'Total',
          Expression: '[github_watchers] + [github_stars]',
          CalculatedColumnSettings: {
            DataType: 'number',
            Aggregatable: true,
            Filterable: false,
          },
        },
        {
          ColumnId: 'Popularity',
          Expression: '[github_watchers] > 500 ? "Popular" : "Unpopular" ',
          CalculatedColumnSettings: {
            DataType: 'boolean',
            Pivotable: true,
            Filterable: false,
          },
        },
        {
          ColumnId: 'Favourites',
          Expression: '[name] IN ("react", "angular", "vue", "stencil") ? "Main" : "Other" ',
          CalculatedColumnSettings: {
            DataType: 'boolean',
            Groupable: true,
            Filterable: false,
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Pivot Layout',
      Layouts: [
        {
          Name: 'Pivot Layout',
          PivotColumns: ['Popularity'],
          PivotGroupedColumns: ['Favourites'],
          SuppressAggFuncInHeader: true,
          PivotAggregationColumns: [
            {
              ColumnId: 'github_watchers',
              AggFunc: 'sum',
            },
            {
              ColumnId: 'github_stars',
              AggFunc: 'sum',
            },
            {
              ColumnId: 'Total',
              AggFunc: 'sum',
            },
          ],
        },
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'github_watchers',
            'language',
            'Total',
            'Popularity',
            'Favourites',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

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

import {rowData, WebFramework} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions<WebFramework> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = ({agGridApi}: AdaptableReadyInfo) => {
  agGridApi.openToolPanel('columns');
};
```

## Calculated Columns Performance

Calculated Columns are designed to be very performant.

However a very large Data Set, with multiple Calculated Columns that reference other Calculated Columns, might present a performance hit.

This could be particularly noticeable when sorting a column and AG Grid's [Value Cache](https://www.ag-grid.com/javascript-data-grid/value-getters/#value-cache) is unset

This is because a Calculated Column contains a [Value Getter](https://www.ag-grid.com/javascript-data-grid/value-getters) which is invoked each time a value is needed.

So when sorting a Column the same Value Getter will be called many times repeatedly.

- In such scenarios, consider setting `valueCache` to *true* in AG Grid GridOptions
- This will enable the [Value Getter Cache](https://www.ag-grid.com/javascript-data-grid/value-getters/#value-cache) (which comes with various Expiry options)

## Using Calculated Columns

Although typically defined at design-time by developers, Calculated Columns also have a rich **run-time** UI.

Users can create, edit, delete and share them via the [Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md) and the Calculated Column Wizard, and can see and, crucially **understand** - Excel-style - how each value is derived using **Formula Trace**.

This displays a list of existing Calculated Columns with buttons to edit, share or delete each item.

- There is no *Suspend* Button as Calculated Columns **cannot** be suspended
- AdapTable will try to prevent you from *deleting* a Calculated Column which is referenced elsewhere

There is also an Add button to create new Calculated Columns using the Calculated Column Wizard.

- Newly created Calculated Columns are automatically added to the end of the Current [Layout](https://www.adaptabletools.com/docs/handbook-layouts/index.md)
- Existing Calculated Columns include an `Edit Calculated Column` Menu Item in the [Column Menu](https://www.adaptabletools.com/docs/ui-column-menu/index.md)

### Using the Calculated Column Wizard

There are a few steps required when creating a Calculated Column:

There are 6 types of Calculated Column which can be created (using the [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md)):

- Standard - value is derived from other cells in Row

- Observable - value is returned by watching for changes (or lack of changes)

- Aggregated - value is derived from aggregating multiple rows

- Cumulative - value is derived cumulatively from other rows

- Quantile - value is derived using quantile aggregations

- Window - value is based on other rows using an ordered series

The Calculated Column Definition step requires 3 properties to be provided:

- `Column Id` - this is the value used to refer to the Calculated Column in the AdapTable UI.

- `Name` (optional) - how the column will be referenced and what to appear in the Column's Header

This property will default to the `ColumnId` value, so only set this if you need it to be different

- Header Tooltip (optional) - a Tooltip to display in the Column's Header

The Expression Editor is a powerful UI tool designed to make writing Expressions easy, including:

- a dropdown that provides all the Expression Functions available
- context sensitive help
- validation

There are 2 settings that can be provided:

- `DataType` - this is the DataType you require for the Column. Options are:
  - String (the default)
  - Number
  - Date
  - Boolean

AdapTable will infer this from the Expression set in the previous stage, so only override if required

- `Cell Data Type` (optional) - a custom [AG Grid Cell Data Type](https://www.adaptabletools.com/docs/dev-guide-aggrid-cell-data-types/index.md) to use for formatting and export

- This dropdown only appears if your application has registered custom AG Grid Cell Data Types (in the `dataTypeDefinitions` property of AG Grid GridOptions) that are compatible with the chosen `DataType`
- See [AG Grid Cell Data Type](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md#ag-grid-cell-data-type) for more details

- `Column Width` - how wide the Calculated Column should be

If left empty, the width will be set by AG Grid based on the other column definitions

There is a set properties that can be configured for the Calculated Column:
- `Filterable`
- `Resizable`
- `Groupable`
- `Sortable`
- `Pivotable`
- `Aggregatable`
- `Suppress Menu`
- `Suppress Movable`
- `Editable` (always false)

All properties are <i>false</i> by default so check an option to turn on a feature

In addition any options that have been supplied in the `columnTypes` property of [Column Options](https://www.adaptabletools.com/docs/technical-reference-column/index.md) will also be displayed.

The new Calculated Column will be created, and will be added to the end of the Current [Layout](https://www.adaptabletools.com/docs/handbook-layouts/index.md).

It will be given, where applicable, any properties defined in AG Grid DefaultColDef.

## Defining Calculated Columns

Calculated Columns can be defined by developers via [Calculated Column Initial Adaptable State](https://www.adaptabletools.com/docs/technical-reference-calculated-column/index.md).

Each `CalculatedColumn` object contains 3 main sets of properties to:

- uniquely identify and name the Calculated Column
- provide the Expression which is to be evaluated
- describe the behaviour of the Column

### Anatomy of a Calculated Column

The [`CalculatedColumn`](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md) object is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [CalculatedColumnSettings](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md#calculatedcolumnsettings) | [`CalculatedColumnSettings`](https://www.adaptabletools.com/docs/reference/calculatedcolumnsettings.md) | Additional optional properties for Column (e.g. filterable, resizable) |
| [ColumnId](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md#columnid) | `string` | Id of the column AdapTable creates. It is not the id of a column already in the data source. |
| [Expression](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md#expression) | `string` | AdapTableQL Expression used to evaluate the Column&#39;s value.<br/><br/>The kind is inferred from the text: a per-row expression such as<br/>`[quantity] * [price]` yields a Standard column; an expression containing<br/>an aggregation such as `SUM{[notional], GROUP_BY([sector])}` or<br/>`[price] / AVG{[price]}` is evaluated over the row set. |
| [FriendlyName](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md#friendlyname) | `string` | Name to be used in Column Header; if blank `ColumnId` is used |
| [Type](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md#type) | [`CalculatedColumnType`](https://www.adaptabletools.com/docs/reference/calculatedcolumntype.md) | Calculated Column category: `Standard` / `Observable` (per-row) or<br/>`Aggregated` / `Cumulative` / `Quantile` / `Window` (over rows).<br/>See . |
| [IsReadOnly](https://www.adaptabletools.com/docs/reference/calculatedcolumn.md#isreadonly) | `boolean` | Sets Entity to ReadOnly (overwriting a Strategy Entitlement of &#39;Full&#39;) |

<b>Calculated Column Settings</b>

The [`CalculatedColumnSettings`](https://www.adaptabletools.com/docs/reference/calculatedcolumnsettings.md) object inherits from the base [`SpecialColumnSettings`](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md) which is defined as follows:

`DataType` is the only mandatory property

| Property | Type | Description | Default |
| --- | --- | --- | --- |
| [Aggregatable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#aggregatable) | `boolean` | Whether Column can be used in an aggregation when grouping | false |
| [CellDataType](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#celldatatype) | `string` | Optional AG Grid `cellDataType` when it differs from `DataType`<br/>(e.g. app-registered `currency` / `percentage` from `dataTypeDefinitions`).<br/>When unset, the ColDef uses `DataType`. |   |
| [ColumnTypes](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#columntypes) | `string[]` | Custom column types added to AG Grid Column Types when object is created |   |
| [DataType](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#datatype) | [`AdaptableColumnDataType`](https://www.adaptabletools.com/docs/reference/adaptablecolumndatatype.md) | Expression&#39;s / column value DataType used by AdapTable (AQL, filters, etc.).<br/> Only mandatory property. |   |
| [Filterable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#filterable) | `boolean` | Whether Column is filterable | false |
| [Groupable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#groupable) | `boolean` | Whether Column can be grouped | false |
| [HeaderToolTip](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#headertooltip) | `string` | Tooltip to show in the Column Header (not cells) |   |
| [Pivotable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#pivotable) | `boolean` | Whether Column can be used when grid is in pivot mode | false |
| [Resizable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#resizable) | `boolean` | Whether Column can be resized (by dragging column header edges) | false |
| [Sortable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#sortable) | `boolean` | Whether Column is sortable | false |
| [SuppressMenu](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#suppressmenu) | `boolean` | Whether if no menu should be shown for this Column header. | false |
| [SuppressMovable](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#suppressmovable) | `boolean` | Whether if this Column should be movable via dragging | false |
| [Width](https://www.adaptabletools.com/docs/reference/specialcolumnsettings.md#width) | `number` | Preferred (pixel) Column Width; if unset, calculated dynamically by AG Grid |   |

There is one additional, optional property added for Calculated Column:

| Property | Type | Description | Default |
| --- | --- | --- | --- |
| [ShowToolTip](https://www.adaptabletools.com/docs/reference/calculatedcolumnsettings.md#showtooltip) | `boolean` | Show underlying Expression as Tooltip when hovering over a cell | false |

- Worked examples of how to define each kind of Calculated Column are on the type-specific pages in this section
- Set `enableFilterOnSpecialColumns` to *false* in [Column Filter Options](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) to disallow filtering on **all** Calculated Columns

## Server-Side Row Model

Calculated Column availability differs according to type when using AG Grid's [Server-Side Row Model](https://www.adaptabletools.com/docs/dev-guide-row-models-server-overview/index.md).

The key consideration is whether AdapTable can see all the rows the expression needs.

- **Standard** and **Observable** - evaluate on the client as each row is rendered
- **Aggregated**, **Cumulative**, **Quantile**, and **Window** need values from many rows. With Server-Side Row Model, those rows are not all on the client, so these expressions are **not** evaluated automatically in the browser.

- See [Server-Side Row Model - Calculated Columns](https://www.adaptabletools.com/docs/dev-guide-row-models-server-calculated-columns/index.md) for what works out of the box and Observable history caveats
- See Guide on [evaluating expressions on the server](https://www.adaptabletools.com/docs/adaptable-server-evaluation/index.md) for dealing with multi-row types

## AG Grid Definitions

Calculated columns are typically **not** provided in the `ColDefs` property in AG Grid GridOptions.

Instead, the definition provided in Initial State suffices for AdapTable to be able to create the associated AG Grid column automatically.

However sometimes a developer might want to add an AG Grid element to the column.

For instance a tooltip might be needed, or there might be a requirement to put the Calculated Column inside a Column Group (which is an AG Grid feature).

This is possible: a column can be provided in AG Grid ColDefs but by specifying a [Column Type](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md) of `calculatedColumn`, AdapTable will automatically wire it up with an associated Calculated Column definition.

- Set the [Column Type](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md) to be `calculatedColumn`
- The `ColId` in the Column Definition and `ColumnId` in the Calculated Column definition must be the same value

**Example: Calculated Columns: Defining in AG Grid**

Calculated Columns: Adding AG Grid properties

- This demo contains an AG Grid Column Group - `Github Averages`
- The group contains 2 Calculated Columns `Github Avg By Language` and `Github Avg By Licence`
- Both the [Column Group](https://www.adaptabletools.com/docs/handbook-grouping-columns/index.md) and the 2 containing Columns were defined in AG Grid Column Defs
- The 2 columns in the Group were given AG Grid Header and Cell ToolTips
- They were also given a type of `calculatedColumn` which is what allowed AdapTable to wire everything together

- Hover over a cell in the Calculated Column and see the Tooltip which AG Grid provides

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  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';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Defining Calculated Columns in AG Grid',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn', 'FormatColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout', 'CalculatedColumn'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'github_stars',
            'license',
            'language',
            'starsAvgByLanguage',
            'starsAvgByLicence',
            'github_watchers',
          ],
          Name: 'Standard Layout',
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'starsAvgByLanguage',
          Expression: 'AVG{[github_stars], GROUP_BY([language])}',
          FriendlyName: 'Github Avg By Language',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'starsAvgByLicence',
          Expression: 'AVG{[github_stars], GROUP_BY([license])}',
          FriendlyName: 'Github Avg By Licence',
          CalculatedColumnSettings: {DataType: 'number'},
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-starsAvgByLanguage',
          Scope: {
            ColumnIds: ['starsAvgByLanguage', 'starsAvgByLicence'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 2,
            },
          },
        },
      ],
    },
  },
};
```

**`src/columnDefs.ts`**

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

export const columnDefs: (ColDef | ColGroupDef)[] = [
  {
    field: 'name',
    cellDataType: 'text',
    sortable: true,
  },

  {
    field: 'language',
    cellDataType: 'text',
    enablePivot: true,
    enableRowGroup: true,
  },
  {
    field: 'github_stars',
    headerName: 'GitHub Stars',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'license',
    cellDataType: 'text',
    editable: false,
    enablePivot: true,
    enableRowGroup: true,
  },
  {
    headerName: 'Github Averages',
    children: [
      {
        colId: 'starsAvgByLanguage',
        type: ['calculatedColumn'],
        cellDataType: 'number',
        headerTooltip:
          "Shows all the Github Stars for the framework's language",
        tooltip: (params: ITooltipParams) => {
          return 'All Stars for ' + params.data.language;
        },
      },
      {
        colId: 'starsAvgByLicence',
        type: ['calculatedColumn'],
        cellDataType: 'number',
        headerTooltip: "Shows all the Github Stars for the framework's licence",
        tooltip: (params: ITooltipParams) => {
          return 'All Stars for ' + params.data.license;
        },
      },
    ],
  },
  {
    field: 'week_issue_change',
    headerName: 'Issue Change',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'created_at',
    headerName: 'Created',
    cellDataType: 'date',
  },
  {
    field: 'has_wiki',
    headerName: 'Has Wiki',
    cellDataType: 'boolean',
    enablePivot: true,
    enableRowGroup: true,
  },
  {
    field: 'updated_at',
    headerName: 'Updated',
    cellDataType: 'date',
  },
  {
    field: 'pushed_at',
    headerName: 'Pushed',
    cellDataType: 'date',
  },
  {
    field: 'github_watchers',
    headerName: 'GitHub Watchers',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'description',
    cellDataType: 'text',
    sortable: false,
  },
  {
    field: 'open_issues_count',
    headerName: 'Open Issues',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'closed_issues_count',
    headerName: 'Closed Issues',
    cellDataType: 'number',
    enableValue: true,
  },

  {
    field: 'open_pr_count',
    headerName: 'Open PRs',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'closed_pr_count',
    headerName: 'Closed PRs',
    cellDataType: 'number',
    enableValue: true,
  },
  {field: 'has_projects', headerName: 'Has Projects', cellDataType: 'boolean'},
  {field: 'has_pages', headerName: 'Has Pages', cellDataType: 'boolean'},
  {
    field: 'topics',
    cellDataType: 'textArray',
    editable: false,
    sortable: false,
  },
  {
    field: 'id',
    cellDataType: 'number',
    hide: true,
    editable: false,
  },
];
```

See [Adding Column Types for Special Columns](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md) for more details and a demo

### AG Grid Cell Data Type

AG Grid provides a [Cell Data Type](https://www.adaptabletools.com/docs/dev-guide-aggrid-cell-data-types/index.md) (`cellDataType`) property which can be attached to one, or more, columns.

AdapTable allows users to leverage, and assign, an _application-registered_ AG Grid Cell Data Type when creating a Calculated Column.

- The `baseDataType` (or `extendsDataType`) must be compatible with the Calculated Column's AdapTable `DataType`
- If this is not provided then AdapTable will use the Calculated Column's `DataType` property

This is done via the optional `CellDataType` property in `CalculatedColumnSettings`:

```tsx {5}
  ColumnId: 'estimated-value',
  Expression: '[bid] * 2',
  CalculatedColumnSettings: {
    DataType: 'number', // AdapTable uses `number` for AQL, filtering and menus...
    CellDataType: 'pricing', // ...but AG Grid renders the cell using the registered `pricing` type
  },
```

- The key benefit is the Calculated Column automatically inherits everything the registered Cell Data Type provides
- e.g. its `valueFormatter`, `valueParser` and cell editor

**Example: Calculated Columns: AG Grid Cell Data Type**

Calculated Columns: Using an AG Grid Cell Data Type

- This demo registers 2 custom AG Grid Cell Data Types in `dataTypeDefinitions` (in AG Grid GridOptions), each with its own `valueFormatter`:
  - `currency` - formats a number as a USD currency value
  - `percentage` - formats a number (0-1) as a percentage
- It then defines 2 Calculated Columns which have an AdapTable `DataType` of `number` but a different `CellDataType`:
  - `Estimated Value` - multiplies `Github Stars` by 5 and renders using the `currency` Cell Data Type
  - `Open Issue %` - divides Open Issues by total Issues and renders using the `percentage` Cell Data Type
- Because the AdapTable `DataType` is still `number`, both columns filter, sort and aggregate as numbers

- Filter or sort the `Estimated Value` Column and note it behaves as a number, even though it displays as currency
- Look at `gridOptions.ts` to see how the `currency` and `percentage` Cell Data Types are registered

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  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';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Calculated Column Cell Data Type',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout', 'CalculatedColumn'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'open_issues_count',
            'closed_issues_count',
            'estimated-value',
            'open-issue-ratio',
          ],
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'estimated-value',
          FriendlyName: 'Estimated Value',
          Expression: '[github_stars] * 5',
          CalculatedColumnSettings: {
            // AdapTable uses `number` for AQL, filtering and menus...
            DataType: 'number',
            // ...but AG Grid renders the cell using the app-registered `currency` type
            CellDataType: 'currency',
          },
        },
        {
          ColumnId: 'open-issue-ratio',
          FriendlyName: 'Open Issue %',
          Expression: '[open_issues_count] / ([open_issues_count] + [closed_issues_count])',
          CalculatedColumnSettings: {
            DataType: 'number',
            CellDataType: 'percentage',
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham, ValueFormatterLiteParams} from 'ag-grid-enterprise';

import {rowData, WebFramework} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions<WebFramework> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  // Application-registered AG Grid Cell Data Types.
  // A Calculated Column can reference these via `CellDataType`.
  dataTypeDefinitions: {
    currency: {
      baseDataType: 'number',
      extendsDataType: 'number',
      valueFormatter: (params: ValueFormatterLiteParams<WebFramework, number>) =>
        params.value == null
          ? ''
          : params.value.toLocaleString('en-US', {
              style: 'currency',
              currency: 'USD',
              maximumFractionDigits: 0,
            }),
    },
    percentage: {
      baseDataType: 'number',
      extendsDataType: 'number',
      valueFormatter: (params: ValueFormatterLiteParams<WebFramework, number>) =>
        params.value == null ? '' : `${(params.value * 100).toFixed(1)}%`,
    },
  },
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

## UI Entitlements

The [UI Entitlements](https://www.adaptabletools.com/docs/handbook-permissioning/index.md) behaviour for Calculated Columns is as expected for `Full` and `Hidden` [`Access Levels`](https://www.adaptabletools.com/docs/reference/accesslevel.md).

The `ReadOnly` Entitlement behaviour is that Calculated Columns will display (and [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) will evaluate their values) but Users are not permitted to edit or delete them.

## Calculated Column Changed Event

The [Calculated Column Changed Event](https://www.adaptabletools.com/docs/technical-reference-calculated-column/index.md) fires whenever anything changes in Calculated Column State, i.e. if a Calculated Column has been added, edited or deleted.

The Event includes details of the Action that triggered the Event and the associated Calculated Column.

This is particularly useful if you are [evaluating Calculated Columns on the Server](https://www.adaptabletools.com/docs/adaptable-server-evaluation/index.md)

### FAQ

**Which mathematical operators can we use to build the Expression?**
AdapTableQL provides a huge number of [Expression Functions](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions/index.md) available to you when writing an Expression.

**Can we add our own Expression Function and reference it when creating the Calculated Column?**
Yes, you can add your own [Custom Expression Functions](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions-custom/index.md) to AdapTableQL which will then be available for your users to use in their own Expressions.

**Can I include more than one operator in an Expression?**
Yes, you can include as many operators as you wish in an [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md).

**Can I use the Calculated Column in other Expressions?**
Yes, once the Calculated Column is created, then its treated the same as any other column and can be referenced other Modules (e.g. [Column Formatting](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md)).

**Can I edit the value a Calculated Column directly?**
No, Calculated Columns are readonly. You can edit the **Expression** but you **cannot** edit a cell in the column itself.

**Can I create a Calculated Column that returns a string?**
Yes, your Calculated Column contains a [Standard Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression-standard/index.md) so it can return a number, string, date or boolean.

**Can I change the name of a Calculated Column?**
You can change the **FriendlyName** of a Calculated Column but, once created, you cannot change the **Id**.
The reason is that the `columnId` could already be being used in other objects like Layouts.

**Can we refer to the Calculated Column in our AG Grid Column Definitions (e.g. to put it in a Column Group)?**
Yes. Ensure the `colId` matches the Calculated Column's `columnID` and add a [Column Type](https://www.adaptabletools.com/docs/dev-guide-columns-column-types/index.md#special-columns) of _calculatedColumn_.

**Can I define the Calculated Column in AdapTable but provide the evaluation myself on my server?**
Yes, return `false` for 'CalculatedColumn' in the `evaluateAdaptableQLExternally` property function in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md).
When this happens AdapTableQL will skip evaluation completely.

**Can my Calculated Column reference other Calculated Columns?**
Yes it can - there are no limits on how many other Calculated Columns a Calculated Column can reference.

**My Grid slows down when sorting referenced Calculated Columns?**
This happens because a Calculated Column contains a [Value Getter](https://www.ag-grid.com/javascript-data-grid/value-getters) which is invoked every time a value is needed.
Enabling the Value Cache (by setting `valueCache` to _true_ in AG Grid GridOptions) will speed things up considerably.

**Can we flash Calculated Columns when they update?**
Yes. Calculated Columns can [flash](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) when a referenced column's value changes — see [Flashing Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-referencing/index.md#flashing-calculated-columns).

**Does AdapTable use AG Grid's Calculated Columns module?**
No. AdapTable Calculated Columns are provided by AdapTableQL and stored in Adaptable State. AG Grid's `CalculatedColumnsModule` is a separate feature — do not register it if you are using AdapTable Calculated Columns (see [AG Grid Modules](https://www.adaptabletools.com/docs/getting-started-aggrid-modules/index.md)).
