6.3 User Defined Functions
To simplify your coding, you could develop a more general function than the ones described above. These are called user defined functions in R, as the user creates them from scratch.
As an example, the function is called simple and requires two input parameters \(i\) and \(t\). The value of \((1 + i*t)\) is calculated.
<- function(i1, t1){
simple 1 + i1*t1
}
Note that the choice of the input parameters \(i1\) and \(t1\) are arbitrary. If \(i = 0.05\) as above and the list of \(t\) remains defined from \([0, 5]\) by \(0.5\) increments, we can evaluate the function as:
<- 0.05
i <- seq(from = 0, to = 5, by = 0.5)
t simple(i, t)
You can verify that your results agree with what you had calculated above.
Try also varying \(i\) from \([0, 0.05]\) by increments of \(0.01\), while keeping \(t\) fixed at 2.
<- seq(from = 0, to = 0.05, by = 0.01)
i <- 2
t simple(i, t)
Thus, by creating this new function, you can calculate many values of accum with just one function.
However, complications occur if you want both \(i\) and \(t\) to be flexible in this function. For example:
<- seq(from = 0, to = 5, by = 0.5)
t <- seq(from = 0, to = .05, by = 0.01)
i simple(i, t)
An error is produced here, as the lengths of \(i\) and \(t\) differ by other than a multiple. (The vector \(t\) is of length 11, while the vector \(i\) is of length 6.) This is a good thing that an error is produced. As had the vectors been a multiple of one another, the end-result of the calculation of the function would not have been correct. Alternatives to this approach will be shown in another tutorial.
Note: Be careful about re-using the same variable names with different meanings, like \(i\) and \(t\) in the same code. Your results may not be what you intend them.