-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3-3_functions_arguments.qmd
75 lines (48 loc) · 2.51 KB
/
3-3_functions_arguments.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Function arguments {.unnumbered}
### Input of Functions
Each function accepts one or more values passed to it as ***arguments***, performs computations or operations on those values, and returns a single result.
To use a function, type the name of the function with the values of its argument(s) in parentheses `( )`, then hit 'Enter'. For example:
```{r}
sqrt(2)
```
Values passed as arguments can be in the form of variables, such as `x` below:
```{r}
x <- 2
sqrt(x)
```
or they can be entire expressions, such as `x^2 + 5` below:
```{r}
sqrt(x^2 + 5)
```
Most functions take multiple arguments, each of which has a name, and some of which are optional. One way to see what arguments a function takes and which ones are optional is to use the function `args().`Another way to view a function's arguments is to look at its help file by typing a `?` in front of the function 's name like so: `?sqrt`
For example, to see what arguments `round()` takes (using `args()`), we'd type:
```{r}
args(round)
```
We see that `round()` has two arguments, `x`, a numeric value to be rounded, and digits, an integer specifying the number of decimal places to round to. Thus to round 4.679 to 2 decimal places, we type:
```{r}
round(4.679, 2)
```
### Optional Arguments and Default Values
The specification `digits = 0` in the output from `args(round)` tells us that digits has a default value of 0. This means that it's an optional argument and if no value is passed for that argument, rounding is done to 0 decimal places (i.e. to the nearest integer).
### Positional Matching and Named Argument Matching
When we type `round(4.679, 2)` R knows, by positional matching, that the first value, 4.679, is the value to be rounded and the second one, 2, is the number of decimal places to round to.
We can also specify values for the arguments by name. For example:
```{r}
round(x = 4.679, digits = 2)
```
When named argument matching is used, as above, the order of the arguments is irrelevant. For example, we get the same result by typing:
```{r}
round(digits = 2, x = 4.679)
```
The two types of argument specification (positional and named argument matching) can be mixed in the same function call:
```{r}
round(4.679, digits=2)
```
Although it may be confusing, it is also possible to specify the first argument in the second position, by using named argument matching for the second argument like so:
```{r}
round(digits=2, 4.679)
```
::: callout-tip
For readability of your code it is advisable to name most of the arguments when calling a function
:::