forked from poole/lanyon
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path05-flow-and-functions.Rmd
432 lines (330 loc) · 10.5 KB
/
05-flow-and-functions.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
---
layout: page
title: 05 -- Functions and control flow
---
# Goals
We are going to build Brownian motion simulator. The idea is simple, start from
a given value (here 0), and at each generation, add a random value drawn from a
normal distribution. It's a commonly used approximation to model ecological and
evolutionary processes. Over time, the value is going on a "random walk".
The function we are going to write won't be particularly elegant or efficient
but will illustrate key programming concepts:
- how to write functions?
- how do conditional statements work?
- how do `for` loops work?
We will also use this example to get familiar with basic plotting functions.
# Step 1: Let's write a basic function
```{r}
sim_brownian <- function() {
seq_len(10)
}
```
The curly brackets delimit the begining and the end of the function. More
generally, the curly brackets delimit a chunk of code that is meaningful in
itself.
with an argument:
```{r}
sim_brownian <- function(ngen) {
seq_len(ngen)
}
```
with an argument and a default value:
```{r}
sim_brownian <- function(ngen=10) {
seq_len(ngen)
}
```
# Step 2: Let's add a `for` loop
```{r}
sim_brownian <- function(ngen=10) {
for (j in seq_len(ngen)) {
message("j is equal to ", j)
}
}
```
```{r}
sim_brownian <- function(ngen=10) {
## create a vector to hold the results
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
message("j is equal to ", j)
tmp_gen[j] <- j * 2
message("tmp_gen[j] is equal to ", tmp_gen[j])
}
tmp_gen
}
```
The function `rnorm()` draws random numbers from a Normal distribution. For
instance, `rnorm(1, mean=2, sd=3)` draws 1 number from a Normal distribution
with a mean 2 (default=0) and a standard deviation of 3 (default=1).
So let's modify our loop so that the vector we return holds the previous value +
a random value drawn from a Normal distribution:
```{r}
sim_brownian <- function(ngen=10) {
## create a vector to hold the results
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
message("j is equal to ", j)
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1)
message("tmp_gen[j] is equal to ", tmp_gen[j])
}
tmp_gen
}
```
Oops... it's not working. Why?
# Step 3: Let's fix the problem
We need to tell our function that it needs to treat the first element of our
vector differently that the rest of it. That's where conditional statements come
to the rescue.
In plain English, we would say, "if this is the first element, give it the value
0, else give it the previous value + a value drawn from a Normal
distribution".
In R these are written like this:
```
if (a condition) {
what to do if the condition is true
} else {
what to do if the condition is false
}
```
let's modify our function:
```{r}
sim_brownian <- function(ngen=10) {
## create a vector to hold the results
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
message("j is equal to ", j)
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1)
}
message("tmp_gen[j] is equal to ", tmp_gen[j])
}
tmp_gen
}
```
## Challenge
Modify the function so that the user can specify the standard deviation of the
Normal distribution from which the random number is drawn from.
# Step 4: Let's add some replicates
Because this is an illustration of a random process, if we want to understand
and visualize the impact of changing the standard deviation on the simulations,
we need to generate replicates under the same conditions.
To do so, we are going to use nested loops. We are going to use a first loop to
create our replicates, and within each replicates, another loop to simulate the
random walk (just like before).
```{r}
sim_brownian <- function(ngen=10, nrep=10, sd) {
## create an empty list to store each replicate
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
## create a vector to hold the results
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
rep_lst
}
```
# Step 5: Let's plot these simulations
```{r}
sim_brownian <- function(ngen=10, nrep=10, sd) {
## create an empty list to store each replicate
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
## create a vector to hold the results
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
plot(seq_len(ngen), rep_lst[[1]], type="l")
rep_lst
}
```
## Challenge
1. Add another argument to your function (call it `draw.plot`) to make the drawing
of the plot optional.
1. This is nice... but it only plot the first replicate. How can we modify the
function so that all replicates are being plotted? You need to use the function `lines()`
hint:
```{r}
sim_brownian <- function(ngen=10, nrep=10, sd) {
## create an empty list to store each replicate
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
## create a vector to hold the results
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
plot(seq_len(ngen), rep_lst[[1]], type="l")
lines(seq_len(ngen), rep_lst[[2]])
rep_lst
}
```
# Step 6: Let's fix the y-axis
We need to identify the minimum and maximum values across all replicates.
Using `plot(..., type="n")` draws an empty plot which is useful to subsequently
draw multiple lines (or other low level functions).
```{r}
sim_brownian <- function(ngen=100, nrep=10, sd=1, draw.plot=TRUE) {
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
if (draw.plot) {
max_y <- max(sapply(rep_lst, max))
min_y <- min(sapply(rep_lst, min))
plot(seq_len(ngen), rep_lst[[1]], lwd=2, type="n",
ylim=c(min_y, max_y))
for (i in seq_len(nrep)) {
lines(seq_len(ngen), rep_lst[[i]])
}
}
rep_lst
}
```
# Step 7: Let's make it prettier
```{r}
sim_brownian <- function(ngen=100, nrep=10, sd=1, draw.plot=TRUE) {
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
if (draw.plot) {
max_y <- max(sapply(rep_lst, max))
min_y <- min(sapply(rep_lst, min))
plot(seq_len(ngen), rep_lst[[1]], lwd=2, type="n",
ylim=c(min_y, max_y))
for (i in seq_len(nrep)) {
lines(seq_len(ngen), rep_lst[[i]], col="gray")
}
}
rep_lst
}
```
## Challenge
1. Use `if/else` so that the last line is drawn using a different color (e.g., "red")
1. Add two arguments to the function, so the user can specify the color s/he
would like for their lines (one argument for the color of the last line
`main.col` and an argument for the other lines `bg.col`).
Let's use the `...` to specify the labels:
```{r}
sim_brownian <- function(ngen=100, nrep=10, sd=1, draw.plot=TRUE, ...) {
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
if (draw.plot) {
max_y <- max(sapply(rep_lst, max))
min_y <- min(sapply(rep_lst, min))
plot(seq_len(ngen), rep_lst[[1]], lwd=2, type="n",
ylim=c(min_y, max_y), ...)
for (i in seq_len(nrep)) {
lines(seq_len(ngen), rep_lst[[i]], col="gray")
}
}
rep_lst
}
```
# Step 8: Let's make it a little safer
This might be unlikely to occur (maybe you are using the function as part of
your workflow and calling it from another function that has a bug in it), but
what would happen if you tried to use the function using `nrep=0`? How about the
number of generations?
```{r}
sim_brownian(nrep=0, plot=FALSE)
sim_brownian(ngen=0, nrep=1, plot=FALSE)
```
Hmm... not so clear what the issue is. Let's create an error message that is
going to be a little more informative in this case.
Also, we may want to warn the user that if less than 10 replicates are used, the
values taken are not going to be very representative of the possible range.
```{r}
sim_brownian <- function(ngen=100, nrep=10, main.col="red",
bg.col="gray50", sd=1, draw.plot=TRUE, ...) {
if (nrep < 1) {
stop("We need at least one replicate.")
}
if (ngen < 2) {
stop("We need at least 2 generations.")
}
if (nrep < 10) {
warning("With less than 10 replicates, the possible range",
"of values may not be very representative.")
}
rep_lst <- vector("list", nrep)
for (i in seq_len(nrep)) {
tmp_gen <- numeric(ngen)
for (j in seq_len(ngen)) {
if (j == 1) {
tmp_gen[j] <- 0
} else {
tmp_gen[j] <- tmp_gen[j - 1] + rnorm(1, sd=sd)
}
}
rep_lst[[i]] <- tmp_gen
}
if (draw.plot) {
max_y <- max(sapply(rep_lst, max))
min_y <- min(sapply(rep_lst, min))
plot(seq_len(ngen), rep_lst[[1]], col=main.col, lwd=2,
type="n", ylim=c(min_y, max_y), ...)
for (i in seq_len(nrep)) {
if (i == max(nrep)) {
lines(seq_len(ngen), rep_lst[[i]], col=main.col,
lwd=2)
} else {
lines(seq_len(ngen), rep_lst[[i]], col=bg.col)
}
}
}
return(rep_lst)
}
```
# Things we didn't cover but need to
* scoping
* `match.arg`