-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path10-more-functions.Rmd
More file actions
500 lines (364 loc) · 9.34 KB
/
Copy path10-more-functions.Rmd
File metadata and controls
500 lines (364 loc) · 9.34 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
---
title: "More about functions"
subtitle: "Stat 133"
author: "Gaston Sanchez"
output: github_document
fontsize: 11pt
urlcolor: blue
---
> ### Learning Objectives
>
> - Naming functions
> - Technicalities of arguments
> - Documenting a function
> - Good practices
```{r setup, include=FALSE}
knitr::opts_chunk$set(error = TRUE)
```
------
## Naming Functions
- Choose meaningful names of functions
- Preferably a verb
- Think about the users (who will use your functions)
- Be consisting with your naming style
### Names of functions
Avoid this:
```{r}
f <- function(x, y) {
x + y
}
```
This is better
```{r}
add <- function(x, y) {
x + y
}
```
## Function Arguments
Functions can have any number of arguments (even zero arguments)
```{r}
# function with 2 arguments
add <- function(x, y) {
z <- x + y
return(z)
}
# function with no arguments
hi <- function() {
print("Hi there!")
}
```
What happens when you call `hi()`?
```{r}
hi()
```
What happens when you pass an input to `hi()`?
```{r}
# be careful
hi('hello')
```
Sometimes is better to give default values to arguments:
```{r}
hey <- function(x = "") {
cat("Hey", x, "\nHow is it going?")
}
hey()
hey("Gaston")
```
If you specify an argument with no default value, you must give it a value
everytime you call the function, otherwise you'll get an error:
```{r}
sqr <- function(x) {
y <- x^2
return(y)
}
# be careful
sqr()
```
### Arguments with no default values
Sometimes you don't want to give default values, but you also don't want to
cause an error. We can use `missing()` to see if an argument is missing:
```{r}
abc <- function(a, b, c = 3) {
if (missing(b)) {
result <- a * 2 + c
} else {
result <- a * b + c
}
return(result)
}
```
### Arguments with no default values
You can also set an argument value to NULL if you don't want to specify a
default value:
```{r}
abcd <- function(a, b = 2, c = 3, d = NULL) {
if (is.null(d)) {
result <- a * b + c
} else {
result <- a * b + c * d
}
return(result)
}
```
Notice that the function `abcd()` can be written as:
```{r}
abcd <- function(a, b = 2, c = 3, d = NULL) {
if (is.null(d)) {
return(a * b + c)
} else {
return(a * b + c * d)
}
}
```
-----
## More Arguments
Consider the following plotting function `myplot()`:
```{r eval = FALSE}
# arguments with and without default values
myplot <- function(x, y, col = "#3488ff", pch = 19) {
plot(x, y, col = col, pch = pch)
}
myplot(1:5, 1:5)
```
- `myplot()` has four arguments
- `x` and `y` have no default values
- `col` and `pch` have default values (but they can be changed)
```{r eval = FALSE}
# changing default values
myplot <- function(x, y, col = "#4286f4", pch = 20) {
plot(x, y, col = col, pch = pch)
}
myplot(1:5, 1:5)
```
### Positional and Named Arguments
There are various kinds of arguments that can be classified in two main groups:
- arguments with default values are known as __named__ arguments.
- arguments with no default values are referred to as __positional__ arguments.
Here's an example of a function containing both types of arguments:
```{r}
omg <- function(pos1, pos2, name1 = 1, name2 = 2) {
(pos1 + name1) * (pos2 + name2)
}
```
- `omg()` has four arguments
- `pos1` is a positional argument
- `pos2` is a positional argument
- `name1` is a named argument
- `name2` is a named argument
### How does R match arguments?
Arguments can be matched positionally or by name
```{r eval=FALSE}
values <- seq(-2, 1, length.out = 20)
# equivalent calls
mean(values)
mean(x = values)
mean(x = values, na.rm = FALSE)
mean(na.rm = FALSE, x = values)
mean(na.rm = FALSE, values)
```
### Partial Matching
Named arguments can also be partially matched:
```{r results='hide'}
# equivalent calls
seq(from = 1, to = 2, length.out = 5)
seq(from = 1, to = 2, length = 5)
seq(from = 1, to = 2, len = 5)
```
`length.out` is partially matched with `length` and `len`
### Examples with `mean()`
```{r results='hide'}
mean(c(NA, 1:9), na.rm = TRUE)
# saving typing
mean(c(NA, 1:9), na.rm = T)
# saving typing but dangerous
mean(c(NA, 1:9), na = T)
```
### Partial matching example
```{r results='hide'}
# Generally you don't need to name all arguments
mean(x = c(NA, 1:9), na.rm = TRUE)
# unusual orders best avoided
mean(na.rm = TRUE, x = c(NA, 1:9))
mean(na = T, c(NA, 1:9))
```
### How many arguments should you remember?
```{r results='hide'}
# Don't need to supply defaults
mean(x = c(NA, 1:9), na.rm = FALSE)
# Need to remember too much about mean()
mean(x = c(NA, 1:9), , TRUE)
# Don't abbreviate too much
mean(c(NA, 1:9), n = T)
```
### Brain Teaser: argument conflict
```{r results='hide'}
f <- function(a = 1, abcd = 1, abdd = 1) {
print(a)
print(abcd)
print(abdd)
}
# what will happen?
f(a = 5)
f(ab = 5)
f(abc = 5)
```
### One more example: naming arguments
Give meaningful names to arguments:
```{r}
# Avoid this
area_rect <- function(x, y) {
x * y
}
```
This is better
```{r}
area_rect <- function(length, width) {
length * width
}
```
Even better: give default values (whenever possible)
```{r}
area_rect <- function(length = 1, width = 1) {
length * width
}
```
Avoid this:
```{r}
# what does this function do?
ci <- function(p, r, n, ti) { p * (1 + r/p)^(ti * p)
}
```
This is better:
```{r}
compound_interest <-
function(principal, rate, periods, time) {
principal * (1 + rate/periods)^(time * periods)
}
```
-----
# Messages
There are two main functions for generating warnings and errors:
- `stop()`
- `warning()`
- There's also the `stopifnot()` function
## Stop Execution
Use `stop()` to stop the execution (this will raise an error)
```{r}
meansd <- function(x, na.rm = FALSE) {
if (!is.numeric(x)) {
stop("x is not numeric")
}
# output
c(mean = mean(x, na.rm = na.rm),
sd = sd(x, na.rm = na.rm))
}
```
## Warning Messages
Use `warning()` to show a warning message
```{r}
meansd <- function(x, na.rm = FALSE) {
if (!is.numeric(x)) {
warning("non-numeric input coerced to numeric")
x <- as.numeric(x)
}
# output
c(mean = mean(x, na.rm = na.rm),
sd = sd(x, na.rm = na.rm))
}
```
A warning is useful when you don't want to stop the execution, but you still
want to show potential problems
## Function `stopifnot()`
`stopifnot()` ensures the truth of expressions:
```{r}
meansd <- function(x, na.rm = FALSE) {
stopifnot(is.numeric(x))
# output
c(mean = mean(x, na.rm = na.rm),
sd = sd(x, na.rm = na.rm))
}
meansd('hello')
```
-----
# Documenting Functions
So far the examples that you've seen in these tutorials are fairly simple.
Moreover, they appear in a somewhat raw format. However, you should strive to
always include _documentation_ for your functions. What does this mean?
Documenting a function involves adding descriptions for the purpose of the
function, the inputs it accepts, and the output it produces.
- Description: what the function does
- Input(s): what are the inputs or arguments
- Output: what is the output (returned value)
You can find some inspiration in the `help()` documentation you when search
for a given function.
## Documenting Functions
Documentation outside the function
```{r}
# Description: calculates the area of a rectangle
# Inputs
# length: numeric value
# width: numeric value
# Output
# area value
area_rect <- function(length = 1, width = 1) {
length * width
}
```
## Documenting Functions
Documentation inside the function's body
```{r}
area_rect <- function(length = 1, width = 1) {
# Description: calculates the area of a rectangle
# Inputs
# length: numeric value
# width: numeric value
# Output
# area value
length * width
}
```
## Roxygen comments
Documentation with roxygen documents (good for packaging purposes)
```{r}
#' @title Area of Rectangle
#' @description Calculates the area of a rectangle
#' @param length numeric value
#' @param width numeric value
#' @return area (i.e. product of length and width)
#' @examples
#' area_rect()
#' area_rect(length = 5, width = 2)
#' area_rect(width = 2, length = 5)
area_rect <- function(length = 1, width = 1) {
length * width
}
```
## Good Principles
- Don't write long functions
- Rewrite long functions by converting collections of related expressions
into separate functions
- A function often corresponds to a verb of a particular step or task in a
sequence of tasks
- Functions form the building blocks for larger tasks
- Write functions so that they can be reused in different settings.
- When writing a function, think about different scenarios and contexts in
which it might be used
- Can you generalize it?
- Avoid hard coding values that the user might want to provide. Make them
default values of new parameters.
- Make the actions of the function as few as possible, or allow the user to
turn off some via logical parameters
- Always test the functions you've written
- Even better: let somebody else test them for you
Separate small functions:
- are easier to reason about and manage
- clearly identify what they do
- are easier to test and verify they are correct
- are more likely to be reusable as they each do less and so you can pick
the functions that do specific tasks
- Make functions parameterizable
- Allow the user to specify values htat might be computed in the function
- This facilitates testing and avoiding recomputing the same thing in
different calls
- Use a default value to do those computations that would be in the body
of the function