Junk Natalia
Junk Natalia

Reputation: 13

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,

Upvotes: 1

Views: 36

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76641

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))

Upvotes: 1

Dave2e
Dave2e

Reputation: 24139

For this problem to handle the compounding of interest it is easier to perform this calculation with a loop.

planned_investments = c(rep(1000, 20), rep(0,5))
overview_invests<- initial_investment
for( i in 1:25) {
   overview_invests<- (overview_invests + planned_investments[i])*(1 + rate)^(1)
   print(overview_invests)
}

There is also the "FinCal" package to handle this.

Upvotes: 1

Related Questions