-
Notifications
You must be signed in to change notification settings - Fork 1
/
functionbasics.Rmd
76 lines (53 loc) · 2.13 KB
/
functionbasics.Rmd
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
# Functions
In programming, a function is a section of a program that **performs a specific task**.
For example, the function **getwd**, that we have seen before, is used as:
```{r, eval=FALSE}
getwd()
```
and has the task of outputting the **current working directory**.
You can recognize a function by its **round brackets**: functionname**()**
A function can also take *arguments/parameters*:
```{r, eval=FALSE}
setwd(dir="Rcourse")
```
**setwd** changes the current working directory to the directory specified with argument **dir**.
<img src="images/func_arg1.png" width="250"/>
* Assign the output of a function to an object:
<img src="images/func_arg2.png" width="250"/>
* Getting help / know how a function works: <br>
From the console:
```{r}
help(getwd)
```
or (shortcut):
```{r}
?getwd
```
From the RStudio bottom-right panel:<br>
<img src="images/func_help.png" width="500"/>
* The help pages show:
+ required/optional argument(s), if any.
+ default values for each argument(s), if any.
+ examples.
+ detailed description.
* Get the example of a function:
```{r, eval=FALSE}
example(mean)
```
* Need more help? Ask your favourite **Web search engine !**
* **Note on arguments**
The help page shows the compulsory arguments in the **Usage** section: in the help page of getwd and setwd (above), you can see that getwd *doesn't take any compulsory argument*, and setwd takes one compulsory argument that is called dir.
<br>
Compulsory arguments can be given **with their names**: in such case you don't need to respect a specific order, or **without their names**, in which case you have to respect the order specified in the help page!<br>
For example, the **rep.int** function (a variant of the rep function) takes 2 arguments (see in help page): **x** and **times**, in that order:
```{r}
# use arguments with their names:
rep.int(x=1, times=3)
# use arguments with their names without respecting the order:
rep.int(times=3, x=1)
# use arguments without their names but respecting the order:
rep.int(1, 3)
# use arguments without their names without respecting the order:
rep.int(3, 1)
# It works, but is not giving the expected output!
```