/
10-functions.qmd
225 lines (180 loc) · 6.12 KB
/
10-functions.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# Functions
Functions should become a really important part of your coding routine.
Basically, consider making this your new moto:
::: {.callout-tip}
## Your new moto
If you need to copy-paste, write a function instead.
:::
## Definition
To get the manual on a base function, type `?function_name`{.R}.
A function returns the last thing that is called in it. Thus a function defined like that will return nothing:
```{r, warnings=FALSE}
geom_mean <- function(x, y){
a <- sqrt(x*y)
}
geom_mean(1,2)
```
While either of these three functions will return what you want:
```{r}
geom_mean1 <- function(x, y){
a <- sqrt(x*y)
a
}
geom_mean2 <- function(x, y){
a <- sqrt(x*y)
return(a)
}
geom_mean3 <- function(x, y){
sqrt(x*y)
}
geom_mean1(1,2) #returns a
```
While an explicit call to `return()`{.R} is not necessary, I think it's usually a good practise to write it explicitly to make clearer to the reader what the function actually returns.
The result of a function can be a list, a data.frame, a vector... or nothing. And you can attribute the result of a function to a variable:
```{r, warnings=FALSE}
person <- function(name, age){
list(name=name, age=age)
}
joe <- person(name="Joe", age=33)
joe
```
## Default values
One can add default values to variables by specifying them in the function definition:
```{r, warnings=FALSE}
testfunc <- function(x, y=1){
x*y
}
testfunc(1)
testfunc(1, y=2)
testfunc(1:3, y=.1)
```
## Passing arguments to other functions
One can also pass arguments to other functions within the function, without have to specify all of them:
```{r, warnings=FALSE}
#| layout-ncol: 2
testfunc2 <- function(x, ...){
y <- sin(x)
plot(x, y, ...)
}
# Here, `...` represents all the arguments you could provide to `plot()`
testfunc2(1:100)
testfunc2(1:100, type="l")
```
You can also pass a function as argument:
```{r, warnings=FALSE}
testfunc3 <- function(FUN, ...){
FUN(...)
}
testfunc3(sum, 1:10)
testfunc3(plot, 1:10, sin(1:10), type="l")
```
## Error handling
It is good practise to handle possible errors in your functions, especially if you share them with others. As a general rule of thumb, you can be sure that *someone* will **always** be able to find the one case where your function does not work or works in an unexpected way.
For this, the easiest way is to use `if()`{.R} statements together with `warning("Warning message")`{.R} or `stop("Stopping message")`{.R}, to either raise a warning while continuing the function, or stop the function altogether with an explanatory message. Alternatively and for ease of reading, the statement `if(condition) stop("Stopping message") `{.R} can be replaced by `stopifnot(condition is true)`{.R}.
Equivalent example with `stop()`{.R} and `stopifnot()`{.R}:
:::: {.columns}
::: {.column width="49%"}
```{r, error=TRUE}
test <- function(x, y) {
if(!is.numeric(x) | !is.numeric(y)){
stop("Both x and y should numeric vectors, buddy!")
}
if(length(x) != length(y)){
if(length(x) == 1 | length(y) == 1){
warning(glue::glue("x has length {length(x)}, while y has length {length(y)}, are you sure?"))
}else{
stop(glue::glue("Both x and y should have same length or length of 1.\n
Here x has length {length(x)}, while y has length {length(y)}."))
}
}
return(x*sqrt(y))
}
```
```{r, error=TRUE}
test(x=1:2,y=1)
test(x=1:2,y="A")
test(x=1:2,y=3:4)
test(x=1:2,y=3:10)
```
:::
::: {.column width="2%"}
:::
::: {.column width="49%"}
```{r, error=TRUE}
test <- function(x, y) {
# the condition is the opposite from the one used in stop():
stopifnot(is.numeric(x), is.numeric(y))
stopifnot(length(x) == length(y) | length(x) == 1 | length(y) == 1)
if(length(x) != length(y) & (length(x) == 1 | length(y) == 1)){
warning(glue::glue("x has length {length(x)}, while y has length {length(y)}, are you sure?"))
}
return(x*sqrt(y))
}
```
<br>
<br>
<br>
<br>
```{r, error=TRUE}
test(x=1:2,y=1)
test(x=1:2,y="A")
test(x=1:2,y=3:4)
test(x=1:2,y=3:10)
```
:::
::::
## Documenting your function
It is also good practise to document your function by describing its purpose, its input parameters, its output, and some use cases. For this, the syntax is as follows:
```{r}
#' Title of the function
#'
#' Description of the function
#'
#' @param param1 Description of param1
#' @param param2 Description of param2
#'
#' @return Description of the output
#'
#' @examples
#' # Some examples on how to use the function
my_func <- function(param1, param2) {
# do some stuff
}
```
RStudio simplifies this process with a tool available in *Code > Insert Roxygen skeleton* (just place your cursor within the `{}` of the function before clicking this).
## Interpolation of data
It is possible to interpolate data through the `approxfun()`{.R} and `splinefun()`{.R} functions: while the former uses linear interpolation, the latter uses cubic splines (polynomials).
```{r}
xmin <- -2*pi; xmax <- 2*pi
x <- runif(30, min=xmin, max=xmax)
xx <- seq(xmin, xmax, .1)
y <- sin(x)
# Linear interpolation
lin_interp <- approxfun(x,y) #is a function
lin_interp(0); lin_interp(pi)
yy_lin <- approx(x, y, xout=xx) #is a list containing x and y
# Cubic spline interpolation
spl_interp <- splinefun(x,y) #is a function
yy_spl <- spline(x, y, xout=xx) #is a list containing x and y
par(family = "Helvetica", cex.lab=1.5, cex.axis=1.4,
mgp = c(2.4, .5, 0), tck=0.02, mar=c(4, 4, 2, .5), lwd=2, las=1)
plot(x, y, pch=16, cex=2, ylim=c(-1,1.6))
lines(xx, lin_interp(xx), col="royalblue") # equivalent to: lines(yy_lin, col="royalblue")
lines(xx, spl_interp(xx), col="red", lty=2)# equivalent to: lines(yy_spl, col="red")
legend("topright",
cex=1.2,
lty=c(NA, 1, 2),
lwd=c(NA, 2, 2),
pch=c(16, NA, NA),
col=c("black", "royalblue", "red"),
bty = "n",
legend=c("'Experimental' points", "Linear interpolation", "Spline interpolation")
)
```
## Exercises {#exo-functions}
<a href="Data/exo-in-class.zip" download target="_blank">Download the archive with all the exercises files</a>, unzip it in your `R class` RStudio project, and edit the R files.
<br>
<br>
<br>
<br>
<br>