`library(FSA) ## for pcumsum(), rcumsum()`

# Introduction

In fisheries analyses it is fairly common to compute the cumulative sum of values in a vector – i.e., all values before and including the current position in the vector. For example, the third value in the cumulative sum would be the sum of the first, second, and third values in the original vector. These types of cumulative sums are easily accomplished with `cumsum()`

in base R.

```
<- 1:10
vec <- cumsum(vec) ) ( cum
```

`#R| [1] 1 3 6 10 15 21 28 36 45 55`

`3] cum[`

`#R| [1] 6`

Some applications in fisheries science (e.g., depletion estimators) require the cumulative sum **NOT** including the current value in the vector. For example, the third value in this case would be the sum of the first and second values in the original vector. These values may be computed by subtracting the original vector from the vector returned by `cumsum()`

.

`-vec cum`

`#R| [1] 0 1 3 6 10 15 21 28 36 45`

In still other applications (e.g., proportional size distribution calculations) a cumulative sum from the **RIGHT** rather than the left is required. For example, the third value in this case would be the sum of the third, fourth, fifth, …, last values in the original vector. These values may be computed by reversing the order of the result from `cumsum()`

that had been applied to the reverse order of the original vector.

`rev(cumsum(rev(vec)))`

`#R| [1] 55 54 52 49 45 40 34 27 19 10`

`FSA`

Functions

For efficiency, these simple processes has been coded in `pcumsum()`

and `rcumsum()`

in **FSA**.

```
## cumsum without the current value
<- pcumsum(vec) ) ( pcum
```

`#R| [1] 0 1 3 6 10 15 21 28 36 45`

`3] pcum[`

`#R| [1] 3`

```
## "reverse" (from the right) cumsum
<- rcumsum(vec) ) ( rcum
```

`#R| [1] 55 54 52 49 45 40 34 27 19 10`

`3] rcum[`

`#R| [1] 52`

The three types of cumulative sums are shown, along with the original vector, in the matrix below.

`cbind(vec,cum,pcum,rcum)`

```
#R| vec cum pcum rcum
#R| [1,] 1 1 0 55
#R| [2,] 2 3 1 54
#R| [3,] 3 6 3 52
#R| [4,] 4 10 6 49
#R| [5,] 5 15 10 45
#R| [6,] 6 21 15 40
#R| [7,] 7 28 21 34
#R| [8,] 8 36 28 27
#R| [9,] 9 45 36 19
#R| [10,] 10 55 45 10
```

These two new functions are unlikely to change the world as we know it; however, I wanted to document them in this blog so that others could find them if needed.^{1}

^{1} The function documentation is available here.

## Reuse

## Citation

```
@online{h.ogle2015,
author = {Derek H. Ogle},
title = {Two {New} {Cumulative} {Sum} {Functions}},
date = {2015-09-06},
url = {https://fishr-core-team.github.io/fishR//blog/posts/2015-9-6_Cumulative_Sums},
langid = {en}
}
```