# sum

> For the complete documentation index, see [llms.txt](https://kotlin.github.io/dataframe/llms.txt).

Computes the [sum](https://en.wikipedia.org/wiki/Summation) of values.

API reference: [sum](https://kotlin.github.io/dataframe/api-docs/core/org.jetbrains.kotlinx.dataframe.api/sum.html)

`null` values are ignored.

All primitive numeric types are supported: `Byte`, `Short`, `Int`, `Long`, `Float`, and `Double`.

`sum` also supports the "mixed" `Number` type, as long as the column consists only of the aforementioned primitive numbers. The numbers are automatically converted to a [common type](numberunification.html) for the operation.

All operations on `Double`/`Float`/`Number` have the `skipNaN` option, which is set to `false` by default. This means that if a `NaN` is present in the input, it will be propagated to the result. When it's set to `true`, `NaN` values are ignored.

```KOTLIN
df.sum() // sum of values per every numeric column
df.sum { age and weight } // sum of all values in `age` and `weight`
df.sumFor(skipNaN = true) { age and weight } // sum of values per `age` and `weight` separately
df.sumOf { (weight ?: 0) / age } // sum of expression evaluated for every row
```

```KOTLIN
df.age.sum()
df.groupBy { city }.sum()
df.pivot { city }.sum()
df.pivot { city }.groupBy { name.lastName }.sum()
```

See [statistics](summarystatistics.html#groupby-statistics) for details on complex data aggregations.

See [column selectors](columnselectors.html) for how to select the columns for this operation.

## Type Conversion

The following automatic type conversions are performed for the `sum` operation:

| Conversion | Result for Empty Input |
| --- | --- |
| Int -> Int | 0 |
| Byte -> Int | 0 |
| Short -> Int | 0 |
| Long -> Long | 0L |
| Double -> Double | 0.0 |
| Float -> Float | 0.0f |
| Number -> Conversion([Common number type](numberunification.html)) -> Number | 0.0 |
| Nothing -> Double | 0.0 |

## Big numbers

> **Warning:**
> `java.math.BigDecimal` and `java.math.BigInteger` are not supported: `sum` throws an exception at runtime for such columns. Compute the sum manually with Kotlin standard library methods and Java big number arithmetic, or [convert](convert.html) the column to a primitive type first.

For a `BigDecimal` column `amount`, the exact sum can be computed with Java `BigDecimal` arithmetic:

```KOTLIN
// exact sum, computed with Java `BigDecimal` arithmetic
df.amount.toList().fold(BigDecimal.ZERO, BigDecimal::add)
```

Alternatively, [convert](convert.html) the column to a primitive type first — at the cost of precision:

```KOTLIN
// approximate sum, computed after converting the column to `Double`
df.convert { amount }.toDouble().sum { amount }
```

