Do not Repeat Yourself - DRY rule
vs. Write Everything Twice - WET rule
Following the WET rule will:
- Increase the difficulty of change
- Decrease clarity
- Leads to opportunities for inconsistency
To prevent duplication and follow the DRY rule, we can write custom functions.
Functions are ‘self contained’ sets of commands that accomplish a specific task.
Functions usually ‘take in’ data or parameter values (these inputs are called ‘function arguments’), process it, and ‘return’ a result. You’ve already used several functions in this tutorial; for example rnorm(n, mean, sd)
, where n
, mean
, and sd
are inputs and the result is a random sample from the normal distribution. The only difference here is that you are writing the function yourself. Once a function is written, it can be used over and over again by calling its name, just like other functions such as rnorm()
.
To write your own function, use the function function
:
<- function(argument1, argument2,…) {
AwesomeFunctionName
do stuff here }
To build up a function, start by writing the “stuff
” to test that it works outside the function.
YOUR TURN:
Create a function that draws a histogram of nrep
mean(rnorm(100))
Modify your function to draw a histogram of nrep
mean(rnorm(n
))
Note that it is useful to define nrep
outside of the function, so users of your script can more easily change that value e.g. from a low number (to verify the script runs without error) to a large number (to obtain reliable results).