Alternative cash flow vector code
In the above example, you may have coded the cash flow vector by writing cf <- c(3, 3, 3, 3, 3, 3, 3, 103).
However, this may seem a bit tedious. An alternative is to code the cash flow vector using the rep()
command. Typing rep(x, y)
will automatically repeat x
y
times. For example, rep(1, 4)
is equivalent to typing c(1, 1, 1, 1)
.
In this exercise, you'll construct a more general function for computing a cash flow vector based on a series of inputs: r
for coupon rate, p
for par value, and ttm
for time to maturity. To do so, you'll take advantage of the rep()
command.
This exercise is part of the course
Bond Valuation and Analysis in R
Exercise instructions
- Code an alternative cash flow function using
rep()
and input variablesr
,p
, andttm
. Save this new function asalt_cf
. - Use
alt_cf
to generate a cash flow vector with coupon rate (r
) of 3% (0.03
), par value (p
) of $100, and time to maturity (ttm
) of 8 years.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Code cash flow function
alt_cf <- function(r, p, ttm) {
c(rep(p * r, ___ - 1), ___ * (1 + ___))
}
# Generate cf vector
alt_cf(r = ___, p = ___, ttm = ___)