<< payments <- function(loan, apr, months) { rate <- 1 + apr / 100 / 12 loan * rate^months * (rate - 1) / (rate^months - 1) } amortize <- function(loan, apr, months, payment = payments(loan, apr, months)) { rate <- 1 + apr / 100 / 12 month <- 0:months balance <- loan * rate^month - payment * (rate^month - 1) / (rate - 1) complete <- match(TRUE, balance <= 0.01) balance <- ifelse(month < month[complete], balance, 0) principal <- loan - balance interest <- payment * month - principal interest <- ifelse(month < month[complete], interest, interest[complete-1]) amrt <- list(month = month[-1], balance=balance[-1], principal = principal[-1], interest = interest[-1], paid = principal[-1] + interest[-1], loan=loan, payment=payment, apr=apr) class(amrt) <- "amortization" return(amrt) } plot.amortization <- function(amrt, ...) { icol <- rgb(189, 215, 231, maxColorValue=255) pcol <- rgb(8, 81, 156, maxColorValue=255) amrt\$paid <- amrt\$paid / 1000 amrt\$principal <- amrt\$principal / 1000 amrt\$interest <- amrt\$interest / 1000 year <- amrt\$month / 12 par(mar = c(4, 1, 1, 5)) plot(0, 0, xlim=range(year), ylim=range(amrt\$paid), type="n", las=1, yaxt="n", main="", cex.main=3, xlab="Year", cex.axis=1.5, cex.lab=1.5, bty="n", ...) axis(4, las=1, cex.axis=1.5, at=pretty(amrt\$paid), labels=paste("\$",pretty(amrt\$paid),"k",sep="")) polygon(c(year,rev(year)), c(amrt\$paid, rev(amrt\$principal)), border=NA, col=icol) polygon(c(year,max(year),0), c(amrt\$principal,0,0), border=NA, col=pcol) text(x=0,y=max(amrt\$paid),adj=c(0,1), cex=2.5, col=icol, font=2, paste("interest \$", round(max(amrt\$interest)), "k", sep="")) text(x=0,y=max(amrt\$paid),adj=c(0,2.5), cex=2.5, col=pcol, font=2, paste("principal \$", round(max(amrt\$principal)), "k", sep="")) } # Default quantities dloan <- 150000 drate <- 4.5 dyears <- 30 dpaymt <- payments(dloan, drate, dyears*12) # Read POST data, draw graphic if(!is.null(POST)) { floan <- as.numeric(POST\$loan) if(length(floan) == 1 && !is.na(floan) && floan > 0) dloan <- floan frate <- as.numeric(POST\$rate) if(length(frate) == 1 && !is.na(frate) && frate >= 0) drate <- frate fyears <- as.numeric(POST\$years) if(length(fyears) == 1 && !is.na(fyears) && fyears > 0) dyears <- fyears dpaymt <- payments(dloan, drate, dyears*12) fpaymt <- as.numeric(POST\$paymt) if(length(fpaymt) > 0 && !is.na(fpaymt) && fpaymt >= dpaymt && fpaymt < dloan) dpaymt <- fpaymt } amrt <- amortize(dloan, drate, dyears*12, dpaymt) amrtpp <- amortize(dloan, drate, dyears*12, dpaymt+1) filename <- paste(paste(sample(letters, 16, replace=TRUE),collapse=''), 'amort.png', sep='', collapse='') dirname <- '/srv/www/biostatmatt.com/public_html/R/MortCalcCache/' png(file=paste(dirname, filename, sep='', collapse=''), type="cairo", height=400, width=600) plot(amrt) dev.off() setContentType("text/html; charset=utf-8") >> MortCalc
MortCalc

loan amount:
interest rate:
years:
min. payment:
payment: