-
Notifications
You must be signed in to change notification settings - Fork 61
/
dry-rule.qmd
39 lines (27 loc) · 1.57 KB
/
dry-rule.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# **D**o not **R**epeat **Y**ourself - DRY rule
## *vs.* **W**rite **E**verything **T**wice - WET rule
<br/>
Following the WET rule will:
* Increase the difficulty of change
* Decrease clarity
* Leads to opportunities for inconsistency
<br/>
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`:
```r
AwesomeFunctionName <- function(argument1, argument2,…) {
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).