# Sum of a Series

I have been trying to find the sum of a series defined by Σ(1+r(i))^1:n in R where i and n is in (1:N). Both i and n are of the same length. The solution needs to be two functions, where function 1 calculates the expression (1+r)^n and the second function 2 recursively calls function 1 to calculate the summation. I am struggling to create a way to call function 1 within function 2 and having it calculate the values recursively.

Example:

Rates   Tenor   Printrest
1.20%   1   1.012
1.35%   2   1.02718225
1.90%   3   1.058089859
2.01%   4   1.082856706
1.80%   5   1.093298847
1.70%   6   1.106434521


Answer 6.379862183

## 1 Answer

I think within and cumsum functions solve your problem. The last row in comp.acc column has what you want.

> data.txt <- 'Rates   Tenor   Printrest
+ 1.20   1   1.012
+ 1.35   2   1.02718225
+ 1.90   3   1.058089859
+ 2.01   4   1.082856706
+ 1.80   5   1.093298847
+ 1.70   6   1.106434521'
>
> df <- read.table(text=data.txt, header = TRUE)
>
> within(df, {
+   comp <- (1 + Rates/100)^(Tenor)
+   comp.acc <- cumsum(comp)
+ })
Rates Tenor Printrest comp.acc     comp
1  1.20     1  1.012000 1.012000 1.012000
2  1.35     2  1.027182 2.039182 1.027182
3  1.90     3  1.058090 3.097272 1.058090
4  2.01     4  1.082857 4.180129 1.082857
5  1.80     5  1.093299 5.273428 1.093299
6  1.70     6  1.106435 6.379862 1.106435

• This is insightful and I will try if I can use this for what I intend to do. However, I was looking at a recursive and nested function. The above data was used as an example. My actual formula is a little more complicated and N is dynamically generated and recursively applied. I am trying to bootstrap (finance) a zero coupon yield curve from fed data. – Drj Sep 24 '15 at 14:49