# payback period calculation in R

``payback_period <- Inf``
2 Likes

@nirgrahamuk has given you the right answer given your specification of the problem. Your issue isn't getting help with R code, it's that there is something wrong with the way you are describing the question.

I have 30 cases like the one I mentioned above, so need to calculate payback periods for all 30 cases, the one above was just a single one of them. Now, out of these 30 cases, some of them has positive cash flows and some of them has negative cash flows. So for some, when I calculate payback period in excel, I get payback periods like 3/4/5, which are all correct. So I want to be able to calculate payback period for those cases which has positive cash flows and will have positive payback period as well. While I calculated them in excel, my supervisors want me to calculate them in R. So I need the payback period calculation codes in R. At least, I should get the same no that I got in excel from the positive cash flows.

Here's a quick and dirty method.

``````initial_investment <- 15
annual_cash_flow <- c(10,20,5)
which(cumsum(annual_cash_flow)>=initial_investment)
``````

generallising and accounting for the failure case :

``````mypayback <- function(initial_investment,
annual_cash_flow){
r1 <- which(cumsum(annual_cash_flow)>=initial_investment)
ifelse(is.na(r1),Inf,r1)
}

mypayback(initial_investment = 15,
annual_cash_flow = c(10,20,5))

mypayback(initial_investment = 63,
annual_cash_flow = rep(-100,12))``````
1 Like

improve precision of payback:

``````mypayback <- function(initial_investment,
annual_cash_flow){
r1 <- which(cumsum(annual_cash_flow)>=initial_investment)

if (!is.na(r1)) {
ttl_cf = cumsum(annual_cash_flow[1:(r1-1)])
pay_back = (initial_investment -  ttl_cf) / annual_cash_flow[r1] + r1 - 1
}

ifelse(is.na(r1), Inf, pay_back)
}

mypayback(initial_investment = 15,
annual_cash_flow = c(10,20,5))

mypayback(initial_investment = 63,
annual_cash_flow = rep(-100,12))

``````

Thank you so much everyone.

Thank you. Is there any similar code for IRR calculation in R as well?

I am using the below code but not sure if it is correct:
...

CF0
 66.332
CF\$Flow
 -140.4418 -140.4891 -140.5481 -140.5939 -140.6614 -140.7156 -140.7849 -140.8675 -140.9387 -141.0249 -138.6678 -138.6678 -138.6678
 -138.6678 -138.6678 -138.6678 -138.6678 -138.6678 -138.6678 -138.6678
library(FinCal)
irr(cf=c(-CF0,CF\$Flow))
...
it gives me the following error:
Error in uniroot(function(r) -1 * pv.uneven(r, subcf) + cf, interval = c(1e-10, :
no sign change found in 1000 iterations

Is the code correct? I ran this code for positive cash flows as well, but the same error appears, so it tells me something is probably wrong.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.