Search code examples
rsummaryfinancial

Amortisation schedule using package financial


How do I read the amortisation schedule produced by tvm() in package financial into a dataframe?

Sample code

y=tvm(pv=10000,i=10,n=10,pmt=NA)
summary.tvm(y)

Results

> summary.tvm(y)

Amortization Table

       Bal    Int   Prin    PMT
1     9037  83.33   -963  -1046
2     8066  75.31   -971  -1046
3     7087  67.22   -979  -1046
4     6099  59.06   -987  -1046
5     5104  50.83   -996  -1046
6     4100  42.53  -1004  -1046
7     3088  34.17  -1012  -1046
8     2067  25.73  -1021  -1046
9     1038  17.22  -1029  -1046
10       0   8.65  -1038  -1046
Total      464.04 -10000 -10464

Clearly it is this summary that I need to assign to a dataframe, when I check the function source code for summary.tvm(), it shows this.

> summary.tvm
function (object, row = 1, ...) 
{
    cat("\nAmortization Table\n\n")
    x = object
    row = x[row, ]
    n = row[2]
    a = row[7]
    i = row[1]/(100 * row[8])
    pv = row[3]
    fv = row[4]
    pmt = row[5]
    days = row[6]
    pyr = row[8]
    bal = pv + a * pmt
    res = c()
    for (k in 1:(n - a)) {
        if (k == 1) {
            int = bal * i * (days/(360/pyr))
            prin = pmt + int
            bal = bal + prin
            prin = prin + a * pmt
            res = rbind(res, c(bal, int, prin, pmt * (1 + a)))
        }
        else {
            int = bal * i
            prin = pmt + int
            bal = bal + prin
            res = rbind(res, c(bal, int, prin, pmt))
        }
    }
    res = rbind(res, c(NA, sum(res[, 2]), sum(res[, 3]), sum(res[, 
        4])))
    colnames(res) = c("Bal", "Int", "Prin", "PMT")
    rownames(res) = c(1:(n - a), "Total")
    print(round(res, 2), na.print = "")
    invisible(res)
}
<bytecode: 0x000000001cd42768>
<environment: namespace:financial>

I think I somehow need to extract res and assign it to a dataframe. How does one do that? I checked the class of the summary.tvm output, it shows a matrix.


Solution

  • Just assign the result to an object. The ˙invisible` part just suppresses printing of the object if it's not assigned to a variable.

    out <- summary.tvm(y)
    

    The result should be a matrix, what makes you think it should be something else? If you want it a data.frame, try as.data.frame(out).

    In a short example:

    > smr <- function(x) {
    +   xy <- matrix(1:x, nrow = 1)
    +   print(xy)
    +   invisible(xy)
    + }
    > out <- smr(10)
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    [1,]    1    2    3    4    5    6    7    8    9    10
    > as.data.frame(out)
      V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
    1  1  2  3  4  5  6  7  8  9  10