A simple amortization function

[This article was first published on Houses of Stones » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I was working on a project yesterday where I needed to amortize out a bunch of loans to calculate the total interest a borrower would pay if he or she paid the minimum monthly payment for the full term of the loan. I couldn’t find any package in R that already contained the necessary math, so I looked around and found this post as well as this one. They both presented the R code to do the basic math involved in amortization, but each function was built to handle only one loan at a time. I had well over 100,000 loans I needed to go through, and loops aren’t all that efficiently implemented in R.

So I revised the code to perform that math on all of the loans at once by organizing everything into matrices that could then be added, subtracted, etc. It only took a little over three seconds to amortize 110,335 loans. I don’t know how long it would have taken to amortize each loan individually – I killed the process after I got tired of waiting for it to finish.

The function takes the following parameters:

  • p_input: the initial principal owed on the loan
  • i_input: the interest rate
  • n_months: the length of the loan term, in months
  • output: format of the output; “list” returns a list of full amortization tables (balance, payment, principal, interest, and installment for each month); “table” combines all the individual tables into one and differentiates loans by a separate index column; “balance”, “payment” “principal”, and “interest” return only those columns
  • index: an id number or other unique identifier for each loan; if not supplied, the loans are just numbered

 

To leave a comment for the author, please follow the link and comment on their blog: Houses of Stones » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.