rtidyversemutate

Balance of deposit account using tidyverse / mutate


I am trying to write a script to get the balance of a deposit account with the following constraints:

Here is my solution so far:

library(tidyverse)

initial_investment <- 22950
rate <- 0.015 


overview_invests <- data.frame(id = 1:25, planned_investments = c(rep(1000, 20), rep(0,5))) %>% 
  rowwise() %>% mutate("balance" = initial_investment * (1 + rate)^id + sum(cumsum(planned_investments) * (1 + rate)^(id:1))) %>% ungroup() 

It works reasonly well but it cannot handle the cases where planned_investments are zero. Indeed, in such cases, the balance drops significantly (I assume that I am only getting the part of the sum from the initial_investment). It's probably quite simple to fix but I have tried multiple approaches unsuccessfully.

Thank you in advance for potential suggestions,


Solution

  • If you want to use the tidyverse, write a function to calculate the compound interests and use it in the pipe.

    compound <- function(x, initial = 0, rate) {
      y <- numeric(length(x))
      y[1L] <- (initial + x[1L])
      for(i in seq_along(x)[-1L]) {
        y[i] <- (y[i - 1L] + x[i])*(1 + rate)
      }
      y
    }
    
    df1 <- data.frame(id = 1:25, planned_investments = c(rep(1000, 20), rep(0,5)))
    initial_investment <- 22950
    rate <- 0.015
    
    df1 %>%
      mutate(balance = compound(planned_investments, initial_investment, rate))