Search code examples
rfinance

What is the total deposit with a fixed monthly interest rate and with more money adding to the deposit each year?


Suppose you have 50 dollars and the fixed monthly interest rate is 5%. After the first year, you add 50 dollars to it for each subsequent years, what is the total amount of money you will get at the end of the three-year period.

I understand in R, it can be simply calculated as

((50 x 1.05^12) +50) x 1.05 ^12) + 50) x 1.05^12 = 540.64

Is there a way I can write a function or loop so when calculating a large number of years, for example, 10 years, 15 years, etc. without typing manually?


Solution

  • You can write a simple loop which might be easy to understand :

    get_calc_year_loop <- function(year) {
       ans <- 0
       for(i in seq_len(year)) {
         ans <- (ans + 50)*1.05^12
       }
       return(ans)
    }
    
    get_calc_year_loop(3)
    #[1] 540.6386
    

    However, you can also do this without loop using Reduce :

    get_calc_year <- function(year) {
       Reduce(function(x, y) (x + 50) * 1.05^12, seq_len(year), init = 0)
    }
    get_calc_year(3)
    #[1] 540.6386