R cumsum() Function - Computing Cumulative Sums
The R cumsum() function is used to compute the cumulative sum of a vector.
A cumulative sum is a sequence obtained by successively adding the current element to all previous elements, widely used in fields such as financial analysis and inventory statistics.
The syntax of the cumsum() function is as follows:
cumsum(x)
Parameter Description:
-
x Input numeric vector.
Example
Create a vector
x
<-
c
(
1
,
2
,
3
,
4
,
5
,
6
)
Compute the cumulative sum
result.
cumsum
<-
cumsum
(
x
)
(
result.
cumsum
)
Compute the cumulative product
result.
cumprod
<-
cumprod
(
x
)
(
result.
cumprod
)
The output of the code above is:
[1] 1 3 6 10 15 21
[1] 1 2 6 24 120 720
cumsum() is very useful when simulating cumulative returns:
Example
Simulate daily returns
returns
<-
c
(
0.02
,
0.01
,
0.03
,
0.015
,
0.005
,
0.02
,
0.01
)
Compute the cumulative return
cumulative
<-
cumsum
(
returns
)
(
paste
(
"Cumulative Return:"
, cumulative
)
)
Compute the cumulative maximum
(
paste
(
"Cumulative Maximum:"
,
cummax
(
cumulative
)
)
)
Compute the cumulative minimum
(
paste
(
"Cumulative Minimum:"
,
cummin
(
cumulative
)
)
)
The output of the code above is:
[1] "累计收益: 0.02" "累计收益: 0.01" "累计收益: 0.04"
[4] "累计收益: 0.055" "累计收益: 0.05" "累计收益: 0.07"
[7] "累计收益: 0.06"
[1] "累计最大: 0.02" "累计最大: 0.02" "累计最大: 0.04"
[4] "累计最大: 0.055" "累计最大: 0.055" "累计最大: 0.07"
[7] "累计最大: 0.07"
[1] "累计最小: 0.02" "累计最小: 0.01" "累计最小: 0.01"
[4] "累计最小: 0.01" "累计最小: 0.01" "累计最小: 0.01"
[7] "累计最小: 0.01"
R Language Examples