I have a large data set (about 200 thousand rows), where each row is a loan. I have a loan amount, the number of payments and payment of a loan. I am trying to get a loan rate. R does not have a function to calculate this (at least at the base of R it does not, and I could not find it). Itβs not so difficult to write both npv and irr functions
Npv <- function(i, cf, t=seq(from=0,by=1,along.with=cf)) sum(cf/(1+i)^t) Irr <- function(cf) { uniroot(npv, c(0,100000), cf=cf)$root }
And you can just do
rate = Irr(c(amt,rep(pmt,times=n)))
The problem is that you are trying to calculate a bid for a large number of payments. Since uniroot is not vectorized, and because rep takes an amazing amount of time, you get a slow calculation. You can do it faster if you do the math and find out that you are looking for the roots of the following equation.
zerome <- function(r) amt/pmt-(1-1/(1+r)^n)/r
and then use this as an input for uniroot. This, on my computer, takes about 20 seconds to work in my 200k database.
The problem is that I'm trying to do some optimization, and this is an optimization step, so I'm trying to speed it up even more.
I tried vectorization, but since uniroot is not vectorized, I cannot go any further. Is there any root search method that is vectorized?
thanks