forked from swcarpentry/r-novice-inflammation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-func-R.Rmd
533 lines (458 loc) · 18.7 KB
/
03-func-R.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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
---
title: "Creating Functions"
teaching: 60
exercises: 30
questions:
- "How do I make a function?"
- "How can I test my functions manually?"
- "How should I document my code?"
objectives:
- "Define a function that takes arguments."
- "Return a value from a function."
- "Test a function manually."
- "Set default values for function arguments."
- "Explain why we should divide programs into small, single-purpose functions."
- "Write documentation comments that can be automatically compiled to R's native help and documentation format."
keypoints:
- "Define a function using `name <- function(...arguments...) {...body...}`."
- "Specify default values for arguments when defining a function using `name = value` in the argument list."
- "Call a function using `name(arg1 = value, ...)`."
- "R looks for variables in the current stack frame before looking for them at the top level."
- "Make code more readable by passing arguments preferably by name."
- "Arguments can be passed by matching based on name, by position, or by omitting them (in which case the default value is used)."
- "Use `?name` or `??name` to find the help page of a function."
- "Write formal roxygen2 comments for your functions and generate help pages from those."
source: Rmd
---
```{r, include = FALSE}
source("../bin/chunk-options.R")
knitr_fig_path("03-func-R-")
```
If we only have one data set to analyze, it would probably be faster to load the file into a spreadsheet and use that to plot some simple statistics.
However, we often have multiple data files or can expect more in the future.
That's why it's usually a good idea to prepare for this case
and write code in a reproducible manner right away.
In this lesson, we'll learn how to write a function so that we can repeat several operations with a single command.
### Defining functions
Let's start by defining a function `fahrenheit_to_kelvin` that converts temperatures from Fahrenheit to Kelvin:
```{r}
fahrenheit_to_kelvin <- function(temp_F) {
temp_K <- ((temp_F - 32) * (5 / 9)) + 273.15
return(temp_K)
}
```
We define `fahrenheit_to_kelvin` by assigning it to the output of `function`.
The arguments are listed within parentheses. In this case, it's only one.
Next, the [body]({{ page.root }}/reference/#function-body) of the function (i.e. the statements that are executed when it runs) is surrounded by `{` curly braces `}`.
The statements in the body are indented by two spaces, which makes the code easier to read but does not affect how the code operates.
When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function.
Inside the function, we use a [return statement]({{ page.root }}/reference/#return-statement) to send a result back to whoever asked for it.
> ## Automatic Returns
>
> In R, it is not necessary to include the return statement.
> R automatically returns the return value of last line of the body
> of the function. While in the learning phase, we will explicitly define the
> return statement.
{: .callout}
Let's try running our function.
Calling our own function is no different from calling any other function:
```{r}
# freezing point of water
fahrenheit_to_kelvin(32)
# boiling point of water
fahrenheit_to_kelvin(212)
```
We've successfully called the function that we defined, and we have access to the value that we returned.
### Composing functions
Now that we've seen how to turn Fahrenheit into Kelvin, it's easy to turn Kelvin into Celsius:
```{r}
kelvin_to_celsius <- function(temp_K) {
temp_C <- temp_K - 273.15
return(temp_C)
}
# absolute zero in Celsius
kelvin_to_celsius(0)
```
What about converting Fahrenheit to Celsius?
We could write out the formula, but we don't need to.
Instead, we can [compose]({{ page.root }}/reference/#function-composition)
a third function from our two previous ones:
```{r}
fahrenheit_to_celsius <- function(temp_F) {
temp_K <- fahrenheit_to_kelvin(temp_F)
temp_C <- kelvin_to_celsius(temp_K)
return(temp_C)
}
# freezing point of water in Celsius
fahrenheit_to_celsius(32.0)
```
This is our first taste of how larger programs are built: we define basic
operations, then combine them in ever-larger chunks to get the effect we want.
Real-life functions will usually be larger than the ones shown here: typically half a dozen to a few dozen lines.
However, they shouldn't ever be much longer than that, or the next person who reads them won't be able to understand what's going on.
> ## Nesting Functions
>
> The previous example showed the output of `fahrenheit_to_kelvin` assigned to `temp_K`, which
> is then passed to `kelvin_to_celsius` to get the final result. It is also possible
> to perform this calculation in one line of code, by "nesting" one function
> inside another, like so:
>
> ```{r chained-example}
> # freezing point of water in Celsius
> kelvin_to_celsius(fahrenheit_to_kelvin(32.0))
> ```
{: .callout}
> ## Create a Function
>
> R has a built-in function to **c**ombine elements into a vector: the `c` function.
> E.g. `x <- c("A", "B", "C")` creates a vector `x` with three elements.
> Furthermore, we can extend that vector again using `c`, e.g. `y <- c(x, "D")` creates a vector `y` with four elements.
> Write a function called `wrapper` that takes two vectors as arguments, called
> `original` and `highlight`, and returns a new vector that has the highlighting
> at the beginning and end of the original:
>
> ```{r, echo=-1}
> wrapper <- function(original, highlight) {
> answer <- c(highlight, original, highlight)
> return(answer)
> }
> best_practice <- c("Write", "programs", "for", "people", "not", "computers")
> dry_principle <- c("Don't", "repeat", "yourself", "or", "others")
> asterisk <- "***" # R interprets a variable with a single value as a vector
> # with one element.
> wrapper(best_practice, asterisk)
> wrapper(dry_principle, asterisk)
> ```
>
> > ## Solution
> > ~~~
> > wrapper <- function(original, highlight) {
> > answer <- c(highlight, original, highlight)
> > return(answer)
> > }
> > ~~~
> > {: .r}
> {: .solution}
{: .challenge}
> ## The Call Stack
>
> For a deeper understanding of how functions work,
> you'll need to learn how they create their own environments and call other functions.
> Function calls are managed via the call stack.
> For more details on the call stack,
> have a look at the [supplementary material](http://swcarpentry.github.io/r-novice-inflammation/14-supp-call-stack/).
{: .callout}
> ## Named Variables and the Scope of Variables
>
> Functions can accept arguments explicitly assigned to a variable name in
> the function call `functionName(variable = value)`, as well as arguments by
> order:
>
> ```{r}
> input_1 <- 20
> mySum <- function(input_1, input_2 = 10) {
> output <- input_1 + input_2
> return(output)
> }
> ```
>
> 1. Given the above code was run, which value does `mySum(input_1 = 1, 3)` produce?
> 1. 4
> 2. 11
> 3. 23
> 4. 30
> 2. If `mySum(3)` returns 13, why does `mySum(input_2 = 3)` return an error?
{: .challenge}
### Testing functions interactively
Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly.
To see how to do this, let's write a function to center a dataset around a particular value.
Please create a new file for this and save it as `center.R`.
```{r}
center <- function(data, desired) {
new_data <- (data - mean(data)) + desired
return(new_data)
}
```
We could test this on our actual data, but since we don't know what the values ought to be, it will be hard to tell if the result was correct.
Instead, let's create a small vector of integers and center it around a small integer,
so that we can comprehend, retrace and therefore check the calculation in our head:
```{r, }
(z <- c(1, 2, 3))
center(z, 3)
```
That looks right, so let's try centering our inflammation data from day 4 around 0:
```{r}
dat <- read.csv(file = "inflammation.csv", header = FALSE)
centered <- center(dat[, 4], 0)
head(centered)
```
It's hard to tell from the default output whether the result is correct, but there is one
test that will reassure us: the standard deviation hasn't changed.
```{r}
# original standard deviation
sd(dat[, 4])
# centered standard deviation
sd(centered)
```
Those values look the same, but we probably wouldn't notice if they were different in the sixth decimal place.
Let's do this instead:
```{r}
# difference in standard deviations before and after
sd(dat[, 4]) - sd(centered)
```
Sometimes, a very small difference can be detected due to rounding at very low decimal places.
R has a useful function for comparing two objects allowing for rounding errors, `all.equal`:
```{r}
all.equal(sd(dat[, 4]), sd(centered))
```
It's still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis.
We have one more task first, though: we should write some [documentation]({{ page.root }}/reference#documentation) for our function to remind ourselves later what it's for and how to use it.
### Documenting functions
A common way to put documentation in software is to add "informal" comments like this:
```{r center-commented, eval=FALSE}
center <- function(data, desired) {
# return a new vector containing the original data centered around the
# desired value.
# Example: center(c(1, 2, 3), 0) should return [1] -1 0 1
new_data <- (data - mean(data)) + desired
return(new_data)
}
```
This is a good practice to begin with. Keeping the documentation exactly next to
the code helps keeping the former in sync with code changes.
However, when using `?…` or `help(…)` we do not see such informal comments.
How can we create conveniently readable help pages for our own functions? By
using the [roxygen2] package!
```{r, eval=FALSE}
install.packages("roxygen2")
library("roxygen2")
```
It can convert "formal" documentation comments (lines starting with `#'`) into the
standard R format for help pages. You will learn more about taking advantage of
this conversion in the [packaging episode]({{ page.root }}/04-making-packages-R/).
> ## Technical details of R's help page format
>
> Help pages are rendered not directly from the roxygen comments, but from
> `.Rd` files that use a markup language similar to [LaTeX].
> [roxygen2] generates those `.Rd` files from the formal function documentation
> comments. Therefore, R coders don't have to write these LaTeX-like files separately,
> but instead document their functions alongside the code.
{: .callout}
[LaTeX]: https://www.latex-project.org/
[roxygen2]: https://cran.r-project.org/package=roxygen2/vignettes/rd.html
For now, let's prepare a solid foundation of using [roxygen2's `#'` notation][roxygen2]
for documenting functions. Please compare the following to the informal comments
we used above and in the ["Analyzing Patient Data" episode]({{ page.root }}/02-starting-with-data/):
```{r center-roxygen}
#' Centering Data
#'
#' @param data The numeric vector to be centered
#' @param desired The numeric value around which the data will be centered
#'
#' @return A new vector containing the original data centered around the desired value.
#' @export
#' @examples
#' center(c(1, 2, 3), 0) # should return [1] -1 0 1
center <- function(data, desired) {
new_data <- (data - mean(data)) + desired
return(new_data)
}
```
Unsurprisingly, the first line should be a short, descriptive title. Additional
text paragraphs are possible after leaving one line blank with only a `#'`.
The descriptive tags (preceded by an `@`) hold the most important details.
Each `@param` documents an input parameter, while `@return` explains the function's
output. The more comprehensible a description of its in- and output data (types), the
easier a function can be integrated into larger analysis pipelines.
`@export` means that the function is presented to users, after we have
[packaged it in a later episode]({{ page.root }}/reference/#packages).
> ## Functions to Create Graphs
>
> To automate the plotting of the graphs from the
> [previous lesson][start-ep] (average inflammation over time),
> we wrote the following function:
> ~~~
> analyze <- function(filename) {
> # Input a character string that correspondes to a filename to
> # to get the average inflammation of each day plotted.
> dat <- read.csv(file = filename, header = FALSE)
> avg_day_inflammation <- colMeans(dat)
> plot(avg_day_inflammation)
> }
> ~~~
> {: .r}
>
> Formalise the above comments into roxygen-style function documentation.
>
> > ## Solution
> > ~~~
> > #' Analyse One of My Patient Inflammation Data Files
> > #'
> > #' @param filename character string of a .csv file
> > #'
> > #' @return Plots the average inflammation over time.
> > #' @export
> > #' @examples
> > #' analyze("inflammation.csv")
> > analyze <- function(filename) { … }
> > ~~~
> > {: .r}
> {: .solution}
{: .challenge}
If you are using RStudio, a nice shortcut is
<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>R</kbd>. Place the
cursor inside the function name or body, press that shortcut,
and a roxygen comment skeleton will be inserted.
## Rescaling
Another example of an informally documented function:
```{r challenge-more-advanced-function-rescale}
rescale <- function(v) {
# takes a vector as input
# returns a corresponding vector of values scaled to the range 0 to 1
# e.g.: rescale(c(1, 2, 3)) => 0.0 0.5 1.0
L <- min(v)
H <- max(v)
result <- (v - L) / (H - L)
return(result)
}
```
Please create a new file for this and save it as `rescale.R`, and test that
it is mathematically correct by using `min`, `max`, and `plot`.
> ## Rescaling documentation
>
> Convert `rescale`'s comments into roxygen function docu! Which keyboard shortcut
> gets you started in RStudio?
>
> > ## Solution
> >
> > Find the keyboard shortcut above, and one possible roxygen documentation below.
> >
> > ~~~
> > #' Rescaling vectors to lie in the range 0 to 1
> > #'
> > #' @param v A numeric vector
> > #'
> > #' @return The rescaled numeric vector
> > #' @export
> > #' @examples
> > #' rescale(c(1, 2, 3)) # should return [1] 0.0 0.5 1.0
> > #' rescale(c(1, 2, 3, 4, 5)) # should return [1] 0.00 0.25 0.50 0.75 1.00
> > rescale <- function(v) { ... }
> > ~~~
> > {: .r}
> {: .solution}
{: .challenge}
[start-ep]: {{ page.root }}/02-starting-with-data/
### Defining defaults
We have passed arguments to functions in two ways: directly, as in `dim(dat)`, and by name, as in `read.csv(file = "inflammation.csv", header = FALSE)`.
In fact, we can pass the arguments to `read.csv` without naming them:
```{r}
dat <- read.csv("inflammation.csv", FALSE)
```
However, the position of the arguments matters if they are not named.
```{r, error = TRUE}
dat <- read.csv(header = FALSE, file = "inflammation.csv")
dat <- read.csv(FALSE, "inflammation.csv")
```
To understand what's going on, and make our own functions easier to use, let's
save our `center.R` file as `center2.R` and re-define the function as follows.
```{r center-default}
#' Centering Data
#'
#' @param data The numeric vector to be centered
#' @param desired The numeric value around which the data should be centered (default = 0)
#'
#' @return A new vector containing the original data centered around the desired value.
#' @export
#' @examples
#' center2(c(1, 2, 3)) # should return [1] -1 0 1
#' center2(c(1, 2, 3), 1) # should return [1] 0 1 2
center2 <- function(data, desired = 0) {
new_data <- (data - mean(data)) + desired
return(new_data)
}
```
The key change is that the second argument is now written `desired = 0` instead of just `desired`.
If we call the function with two arguments, it works as it did before:
```{r}
test_data <- c(1, 2, 3)
center2(test_data, 3)
```
But we can also now call `center2()` with its first argument only, in which case `desired` is automatically assigned the default value of `0`:
```{r}
(more_data <- 5 + test_data)
center2(more_data)
```
This is handy: if we usually want a function to work one way, but occasionally need it to do something else, we can allow people to pass an argument when they need to but provide a default to make the normal case easier.
> ## Matching Arguments
>
> To be precise, R has three ways that arguments supplied
> by you are matched to the *formal arguments* of the function definition:
>
> 1. by complete name,
> 2. by partial name (matching on initial *n* characters of the argument name), and
> 3. by position.
>
> Arguments are matched in the manner outlined above in *that order*: by
> complete name, then by partial matching of names, and finally by position.
{: .callout}
> ## A Function with Default Argument Values
>
> Save the `rescale` function as `rescale2.R` and rewrite it to scale a vector to lie between 0 and 1 by default, but will allow the caller to specify lower and upper bounds if they want.
> Compare your implementation to your neighbor's: do the two functions always behave the same way?
>
> > ## Solution
> > ~~~
> > #' Rescaling Vectors To Lie In A Lower- And Upper-Bounded Range
> > #'
> > #' @param v A numeric vector
> > #' @param lower numeric (default = 0)
> > #' @param upper numeric (default = 1)
> > #'
> > #' @return The rescaled numeric vector
> > #' @export
> > #' @examples
> > #' rescale2(c(1, 2, 3)) # should return [1] 0.0 0.5 1.0
> > #' rescale2(c(1, 2, 3), 1, 2) # should return [1] 1.0 1.5 2.0
> > rescale2 <- function(v, lower = 0, upper = 1) {
> > L <- min(v)
> > H <- max(v)
> > result <- (v - L) / (H - L) * (upper - lower) + lower
> > return(result)
> > }
> > ~~~
> > {: .r}
> {: .solution}
{: .challenge}
```{r, include=FALSE}
#' Rescaling Vectors To Lie In A Lower- And Upper-Bounded Range
#'
#' @param v A numeric vector
#' @param lower numeric (default = 0)
#' @param upper numeric (default = 1)
#'
#' @return The rescaled numeric vector
#' @export
#' @examples
#' rescale2(c(1, 2, 3)) # should return [1] 0.0 0.5 1.0
#' rescale2(c(1, 2, 3), 1, 2) # should return [1] 1.0 1.5 2.0
rescale2 <- function(v, lower = 0, upper = 1) {
L <- min(v)
H <- max(v)
result <- (v - L) / (H - L) * (upper - lower) + lower
return(result)
}
```
```{r rescale-test}
rescale2(v = dat[, 4], lower = 2, upper = 5))
rescale2(dat[, 4], -5, -2))
```
Compare both `rescale2` calls: Which is more understandable? Although passing
arguments purely by position is very convenient, because you have to type less,
it's usually better to write the argument name. Most code is more often read,
than edited, so the reader (maybe your future self) may loose more time
understanding the code (e.g. by having to look up non-obvious details) than you
saved by typing less. Also, a good IDE (integrated development environment) will
reduce your typing with auto-completion. Thus, it is generally better to only omit
an argument name if its value clarifies it. For example, `read.csv("path/to/file.xyz")`
is comprehensible even without `...(file = "...` in the middle.