I've just started learning R, but I feel that I'm using it only as a normal procedural language without taking advantage of some built-in functions and data structures.
I wrote a function that calculates repayments for mortgage with an option of specifying list of overpayments to reduce monthly payments. Please suggest any improvements on making it more native to R.
source("http://pastebin.com/raw.php?i=q7tyiEmM") ## for pmt()
mortgage <- function(price=1000000, deposit=0.10, rate=0.04, years=25, over=c()) {
loan <- price - price * deposit
months <- years * 12
capital <- c()
interest <- c()
payments <- c()
currentCapital <- loan
monthlyRate <- rate / 12
payment <- -pmt(monthlyRate, nper = months + 1, pv = loan)
cat("Initial capital: ", loan, "\n")
cat("Months: ", months, "\n")
cat("Payment: ", payment, "\n")
totalShouldPay <- payment * months
totalPaid <- 0
for(currentMonth in 1:months) {
interest <- currentCapital * monthlyRate
repaid <- payment - interest
currentCapital <- currentCapital - repaid
overPayments <- subset(over, over$month == currentMonth)
if (length(overPayments) > 0 && nrow(overPayments) > 0) {
overPayments <- sum(overPayments$payment)
currentCapital <- currentCapital - overPayments
payment <- -pmt(monthlyRate, nper = months + 1 - currentMonth, pv = currentCapital)
}
capital <- append(capital, currentCapital)
totalPaid <- totalPaid + payment
payments <- append(payments, payment)
}
cat("Would have paid: ", round(totalShouldPay, 2), "\n")
cat("Will pay: ", round(totalPaid, 2), "\n")
cat("Saved: ", round(totalShouldPay - totalPaid, 2), "\n")
return(data.frame(capital=capital, payments=payments))
}
overPayments <- data.frame(
month = c(20, 25, 30, 35, 40),
payment = c(20000, 20000, 20000, 20000, 20000))
cap <- mortgage(
over = overPayments
)
#print(cap)
par(mfcol=c(1, 2))
plot(cap$payments, type="s", main = "Payments", xlab = "Month", ylab = "Payment")
plot(cap$capital, type="l", main = "Capital", xlab = "Month", ylab = "Remaining loan")
payment
after each iteration? Usually, the monthly payment is fixed at the beginning and remains the same throughout the loan's life. If you ever prepay (yourover
), then it means your mortgage will end before its scheduled maturity (years
), whenever the lastpayment
is greater thancurrentCapital
. This is at least how vanilla fixed mortgages in the US work. I can help you with the code but I need an answer to that question. \$\endgroup\$