Aite97
Aite97

Reputation: 165

How do I store the values from a loop in a dataframe in R?

I'm n making a program that compares owning vs renting apartments. As a part of the program I want to create a dataframe of an annuity loan with the interest and principal payments and the remaining balance. The calculations for the loan are easy, but I struggle storing it.

I am new to R, and I'm trying to use it for a project in school instead of Excel. I tried to just store it in a dataframe, but got traceback errors, and I am kinda slow. I looked up code online, but do not want to rip it off 100% either and it was monthly basis. Also tried a similar mortgage function in the FinancialMath package but didn't get a dataframe with desired output. What is important isn't really this mortgage part, but it is essential for my calculations in the rest of my program.

Snippet of the mortgage function from my project, uses yearly basis where P is principal amount, I is interest rate, N is number of years

    mortgage <- function(P=100000, I=1, N=10, amort=TRUE) {
     I <- I/100
     PMT <- (I*P)/(1-(1+I)^(-N))
     if(amort==TRUE) {
      Pt <- P
      currP <- NULL
      while(Pt>=0) {
        H <- Pt * I
        C <- PMT - H
        Q <- Pt - C
        Pt <- Q
        currP <- c(currP, Pt)
      }
    }
  }

A dataframe with the variables year, remaining balance, PMT, interest payment, principal payment. Want to differentiate my code somewhat, but similar result to (minus the plot) as http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/My_R_Scripts/mortgage.R

Upvotes: 1

Views: 87

Answers (0)

Related Questions