title: Pricing multiple bonds in R using loop
body: <p>I am new to R. I was trying to price 20 bonds using one function that I created which is as follows.I can use the <code>Bond_function(FV,coupon,y,freq,T_mat)</code> 20 times entering different values from csv. But I was hoping if I can loop it and stack all the data in a vector/matrix so that it can be done in one code instead of running it 20 times individually.
  for example;  I tried</p>
  <pre><code>bond_1 &lt;- Bond_function(100,2.75,2.88,1,2) 
  </code></pre>
  <p>and did the same thing 20 times then assigned it to a data frame. I was trying to loop it 20 time directly from the csv file so that I can use one code and be done with it. maybe an apply function?</p>
  <p>Need help with this. Thanks!</p>
  <pre><code>rm(list = ls())
  Bond_function &lt;- function(FV,coupon,y,freq,T_mat){
    y_d &lt;- y/freq
    DF &lt;- 1/(1+y_d/100)
    C1 &lt;- sort(rep(1:T_mat,freq))
    C2 &lt;- 1:T_mat*freq
    N_p &lt;- length(C2)
    C3 &lt;- rep(coupon/freq,N_p)
    C3[N_p] &lt;- C3[N_p] + FV
    C4 &lt;- DF^(1:N_p) * C3
    Bond_price &lt;- sum(C4)
    C5 &lt;- C4/Bond_price
    C6 &lt;- C2/freq
    C7 &lt;- C6*C5
    Macaulay_duration &lt;- sum(C7)
    results &lt;- c(Bond_price,Macaulay_duration)
    return(results)
  }
  </code></pre>
  <p>FV and freq are fixed so I will be using the same value for each bond. However I have data available in a csv format that I would like to use for coupon, yield and T_mat. The data from csv is as follows.</p>
  <pre><code>   Number Coupon  Price Yield Maturity Period
  1       1   2.75  99.74  2.88        2      1
  2       2   2.88  99.11  3.07        5      1
  3       3   2.88  97.00  3.23       10      1
  4       4   3.00  92.47  3.40       30      1
  5       5   1.50 100.06  1.47        2      2
  6       6   1.50 100.50  1.40        5      2
  7       7   1.63 100.55  1.56       10      2
  8       8   2.25 104.28  2.06       30      2
  9       9   1.13 101.57  0.31        2      3
  10     10   1.13 103.25  0.46        5      3
  11     11   1.50 106.20  0.85       10      3
  12     12   2.00 114.17  1.42       30      3
  13     13   0.13  99.95  0.15        2      4
  14     14   0.25  99.45  0.36        5      4
  15     15   0.63  98.19  0.82       10      4
  16     16   1.38  94.69  1.60       30      4
  17     17   0.13  99.93  0.16        2      5
  18     18   0.75  99.42  0.87        5      5
  19     19   1.13  95.19  1.66       10      5
  20     20   1.88  90.48  2.32       30      5
  </code></pre>