forked from dcossyleon/basic-course-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc.Rmd
343 lines (275 loc) · 12.9 KB
/
func.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
---
title: "Lecture 3: Functions"
pagetitle: "Lecture 3: Functions"
questions:
- "How do I make a function?"
- "How can I test my functions?"
- "How should I document my code?"
objectives:
- "Define a function that takes arguments."
- "Return a value from a function."
- "Test a function."
- "Set default values for function arguments."
- "Explain why we should divide programs into small, single-purpose functions."
keypoints:
- "Define a function using `name <- function(...args...) {...body...}`."
- "Call a function using `name(...values...)`."
- "R looks for variables in the current stack frame before looking for them at the top level."
- "Use `help(thing)` to view help for something."
- "Put comments at the beginning of functions to provide help for that function."
- "Annotate your code!"
- "Specify default values for arguments when defining a function using `name = value` in the argument list."
- "Arguments can be passed by matching based on name, by position, or by omitting them (in which case the default value is used)."
source: Rmd
---
<!-- ```{r, include = FALSE}
source("../bin/chunk-options.R")
knitr_fig_path("02-func-R-")
``` -->
```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = TRUE)
```
If we only had 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.
But we have twelve files to check, and may have more in the future.
In this lesson, we'll learn how to write a function so that we can repeat several operations with a single command.
### Defining a Function
You can write your own functions in order to make repetitive operations using a single command. Let's start by defining your function "my_function" and the input parameter(s) that the user will feed to the function. Afterwards you will define the operation that you desire to program in the body of the function within curly braces ({}). Finally, you need to assign the result (or output) of your function in the return statement.
```{r, include = FALSE}
my_function <- function(input) {
# perform action and produce output
return(output) # return output value
}
```
Now let's see this process with an example. We are going to define a function `fahrenheit_to_celsius` that converts temperatures from [Fahrenheit to Celsius](https://en.wikipedia.org/wiki/Temperature_conversion_formulas#Fahrenheit):
```{r}
fahrenheit_to_celsius <- function(temp_F) {
temp_C <- (temp_F - 32) * 5 / 9
return(temp_C)
}
```
We define `fahrenheit_to_celsius` by assigning it to the output of `function`.
The list of argument names are contained within parentheses.
Next, the **body** of the function--the statements that are executed when it runs--is contained within 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** 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 whichever variable is on the last line of the body
of the function. While in the learning phase, we will explicitly define the
return statement.
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_celsius(32)
# boiling point of water
fahrenheit_to_celsius(212)
# pizza oven temperature
fahrenheit_to_celsius(700)
```
We've successfully called the function that we defined, and we have access to the value that we returned.
### Exercise: Composing Functions
Now that we've seen how to turn Fahrenheit into Celsius, it's easy to turn Celsius into Kelvin:
Hint: temp_C + 273.15
Calculate freezing point of water in Kelvin
```{r, echo = FALSE}
celsius_to_kelvin <- function(temp_C) {
temp_K <- temp_C + 273.15
return(temp_K)
}
# freezing point of water in Kelvin
celsius_to_kelvin(0)
```
What about converting Fahrenheit to Kelvin?
We could write out the formula, but we don't need to.
Instead, we can [compose]({{ page.root }}/reference.html#function-composition) the two functions we have already created:
```{r}
fahrenheit_to_kelvin <- function(temp_F) {
temp_C <- fahrenheit_to_celsius(temp_F)
temp_K <- celsius_to_kelvin(temp_C)
return(temp_K)
}
# freezing point of water in Kelvin
fahrenheit_to_kelvin(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--but they shouldn't ever be much longer than that, or the next person who reads it won't be able to understand what's going on.
## Exercise: 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?
## Testing, Error Handling, and Documenting
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 midpoint:
```{r}
center <- function(data, midpoint) {
new_data <- (data - mean(data)) + midpoint
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 vector of 0s and then center that around 3.
This will make it simple to see if our function is working as expected:
```{r, }
z <- c(0, 0, 0, 0)
z
center(z, 3)
```
### Dataset
We are studying inflammation in patients who have been given a new treatment for
arthritis, and need to analyze the first dozen data sets.
The data sets are stored in **comma-separated values**
(CSV) format. Each row holds the observations for just one patient. Each column
holds the inflammation measured in a day, so we have a set of values in
successive days.
That looks right, so let's try center on our real data. We'll center the inflammation data from day 4 around 0:
[download this](data/inflammation-01.csv)
```{r}
dat <- read.csv(file = "data/inflammation-01.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 are a few simple tests that will reassure us:
```{r}
dat <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
# original mean
mean(dat[, 4])
# centered mean
mean(centered)
```
That seems right: the original mean was about `r round(mean(dat[, 4]), 2)` and the mean of the centered data is `r mean(centered)`.
We can even go further and check that 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.
However, there are two other important tasks to consider: 1) we should ensure our function can provide informative errors when needed, and 2) we should write some **documentation** for our function to remind ourselves later what it's for and how to use it.
```{r, eval = FALSE}
dat[, 4] <- centered
write.table(dat, file = "inflammation-centered.csv", col.names = FALSE, row.names = FALSE, quote = FALSE, sep = ",")
```
#### Documentation
A common way to put documentation in software is to add **comments** like this:
```{r}
center <- function(data, midpoint) {
# return a new vector containing the original data centered around the
# midpoint.
# Example: center(c(1, 2, 3), 0) => c(-1, 0, 1)
new_data <- (data - mean(data)) + midpoint
return(new_data)
}
```
## Writing Documentation
Formal documentation for R functions is written in separate `.Rd` using a
markup language similar to [LaTeX][]. You see the result of this documentation
when you look at the help file for a given function, e.g. `?read.csv`.
The [roxygen2][] package allows R coders to write documentation alongside
the function code and then process it into the appropriate `.Rd` files.
You will want to switch to this more formal method of writing documentation
when you start writing more complicated R projects.
[LaTeX]: https://www.latex-project.org/
[roxygen2]: https://cran.r-project.org/package=roxygen2/vignettes/rd.html
```{r challenge-more-advanced-function-analyze, eval=FALSE, include=FALSE}
analyze <- function(filename) {
# Plots the average, min, and max inflammation over time.
# Input is character string of a csv file.
dat <- read.csv(file = filename, header = FALSE)
avg_day_inflammation <- apply(dat, 2, mean)
plot(avg_day_inflammation)
max_day_inflammation <- apply(dat, 2, max)
plot(max_day_inflammation)
min_day_inflammation <- apply(dat, 2, min)
plot(min_day_inflammation)
}
```
## Exercise: Functions to Create Graphs
Write a function called `analyze` that takes a filename as an argument
and displays the three graphs produced in the (average, min and max inflammation over time).
`analyze("data/inflammation-01.csv")` should produce the graphs already shown,
while `analyze("data/inflammation-02.csv")` should produce corresponding graphs for the second data set.
Be sure to document your function with comments.
[download this](data/inflammation-02.csv)
### Saving Plots to a File
So far, we have built a function `analyze` to plot summary statistics of the inflammation data:
```{r analyze}
analyze <- function(filename) {
# Plots the average, min, and max inflammation over time.
# Input is character string of a csv file.
dat <- read.csv(file = filename, header = FALSE)
avg_day_inflammation <- apply(dat, 2, mean)
plot(avg_day_inflammation)
max_day_inflammation <- apply(dat, 2, max)
plot(max_day_inflammation)
min_day_inflammation <- apply(dat, 2, min)
plot(min_day_inflammation)
}
```
And also built the function `analyze_all` to automate the processing of each data file:
```{r analyze_all}
analyze_all <- function(folder = "data", pattern) {
# Runs the function analyze for each file in the given folder
# that contains the given pattern.
filenames <- list.files(path = folder, pattern = pattern, full.names = TRUE)
for (f in filenames) {
analyze(f)
}
}
```
While these are useful in an interactive R session, what if we want to send our results to our collaborators?
Since we currently have 12 data sets, running `analyze_all` creates 36 plots.
Saving each of these individually would be tedious and error-prone.
And in the likely situation that we want to change how the data is processed or the look of the plots, we would have to once again save all 36 before sharing the updated results with our collaborators.
Here's how we can save all three plots of the first inflammation data set in a pdf file:
```{r, results='hide', eval = FALSE}
pdf("inflammation-01.pdf")
analyze("data/inflammation-01.csv")
dev.off()
```
The function `pdf` redirects all the plots generated by R into a pdf file, which in this case we have named "inflammation-01.pdf".
After we are done generating the plots to be saved in the pdf file, we stop R from redirecting plots with the function `dev.off`.
> ## Overwriting Plots
>
> If you run `pdf` multiple times without running `dev.off`, you will save plots to the most recently opened file.
> However, you won't be able to open the previous pdf files because the connections were not closed.
> In order to get out of this situation, you'll need to run `dev.off` until all the pdf connections are closed.
> You can check your current status using the function `dev.cur`.
> If it says "pdf", all your plots are being saved in the last pdf specified.
> If it says "null device" or "RStudioGD", the plots will be visualized normally.
{: .callout}
We can update the `analyze` function so that it always saves the plots in a pdf.
But that would make it more difficult to interactively test out new changes.
It would be ideal if `analyze` would either save or not save the plots based on its input.
```{r knit_exit, include=F, echo=F}
knit_exit()
```