Basic skills in R: Working with functions
Why use functions, anyway?
The concept of function in R should be broadly understood: it are not only mathematical functions but also general procedures, consisting of instructions that together define an algorithm that you plan to use repeatedly. For example, if you often have to compute the average of a list of a set of numeric values, it is useful to have a specific function for this, because this way you avoid code repetition and you improve the readability of the program code. If a desired function is not built into R by default (for computing averages we have the built-in function mean
), you will have to define it yourself.
Aside from grouping instructions and avoiding repeated use of the same block of code, there are more reasons to want functions. This way you can split a problem into smaller sub problems. This is called top-down program design . Functions can also be beneficial for other issues. In other words, reusing code becomes possible. In fact, many of the built-in R functions are nothing more than part of collections of procedures defined in the R language. This is what you will learn at a basic level in this sub section.