A simple amortization function

August 29, 2013

(This article was first published on Houses of Stones » R, and kindly contributed to R-bloggers)

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 his blog: Houses of Stones » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.