-
Notifications
You must be signed in to change notification settings - Fork 5
/
intro.Rmd
500 lines (349 loc) · 11.4 KB
/
intro.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
---
title: 'Introduction to R Functions'
subtitle: 'R Ladies Chicago and R Ladies East Lansing'
author: 'Stephanie Kirmer <br> <a href="http://github.com/skirmer">`r icon::fontawesome(name="github")` skirmer</a><br> <a href="http://twitter.com/data_stephanie"> `r icon::fontawesome(name="twitter")` @data_stephanie</a><br> <a href="http://www.stephaniekirmer.com"> `r icon::fontawesome(name="link")` stephaniekirmer.com</a>'
date: 'February 26, 2021'
output:
xaringan::moon_reader:
css: ['xaringan-themer.css', 'extracss.css']
nature:
highlightLines: true
includes:
in_header: header.html
---
layout: true
.footer[<a href="https://github.com/skirmer/functions_r">`r icon::fontawesome(name="github")` github.com/skirmer/functions_r </a> | <a href="http://twitter.com/data_stephanie">`r icon::fontawesome(name="twitter")` @data_stephanie</a>]
---
```{r xaringan-themer, include=FALSE, warning=FALSE}
library(xaringanthemer)
library(countdown)
library(icon)
style_duo_accent(
primary_color = "#23395b",
secondary_color = "#136f63",
header_font_google = google_font("Fira Sans"),
text_font_google = google_font("Droid Serif"),
code_font_google = google_font("Fira Mono")
)
```
# Overview
- Lecture alternating with breakouts for hands-on examples
--
- Repo: https://github.com/skirmer/functions_r
--
- Support Team for questions/leading breakouts
--
<img src="https://media.giphy.com/media/l46Cbqvg6gxGvh2PS/giphy.gif" style="width: 50%" />
???
Introductions for support team
---
## Breakout Sections
- Work through examples in small groups
- 5-ish minute chunks
- Choose either Beginner or Advanced group
- Beginners will read provided function, and gradually edit it
- Advanced will write your own function, and fully develop it
<img src="https://media.giphy.com/media/3jN3GziOKUEmI/giphy.gif" style="width: 30%" />
???
If you have your own code, or some idea for a function, you can work with Advanced group to develop it into a full function
If you don't have your own code or don't want to write it all yourself, work with Beginner
You can change groups later!
---
# What is a Function Anyway?
![](function_diagram.png)
???
You have one thing, and you want to have another thing, so the function is your path to get there.
---
# Why Functions?
- Avoid repetition
- Share code with others
- Eventually build packages
<img src="https://media.giphy.com/media/20BoPFWiCG3K9GYABQ/giphy.gif" style="width: 40%" />
???
Those operations you want to run in order to get from what you have to what you need are useful to others!
This framework is common to many programming languages
---
# Basic Structure
```{r, echo=TRUE, eval=FALSE}
myFunction <- function(){
...
return()
}
myFunction()
```
???
This shell is what lets R know that you intend to create a function.
Now we need to add in the contents.
---
# Basic Structure
```{r, echo=TRUE, eval=FALSE}
myFunction <- function(ARGUMENTS){
{{...}}
return(OUTPUT)
}
myFunction(ARGUMENTS)
```
---
# Basic Structure
```{r, echo=TRUE, eval=FALSE}
myFunction <- function(a, b){
{{c <- a*b}}
return(c)
}
myFunction(a = 2,b = 4)
```
---
class: inverse
# Practice Break 1
Open possible_dog_part1.R and follow the instructions.
- Beginner: Read the sample function, and interpret what it does.
- Discuss the structure. Think about what might make it better or easier to use.
- Advanced: Take a bit of your own code and place it in a function structure. Change function name to something appropriate.
```{r, echo=FALSE}
countdown(minutes = 5, seconds = 0, left=0)
```
---
# Types
- Logical or Boolean (TRUE, FALSE, 0, 1)
- Integer (Numeric) (3, 7, 108)
- Double or Float (Numeric) (1.6645, 3.14159, 987.99)
- Character or String ("Hello", "a")
- Closure (function) (`sum()`)
More info in help: `?type` or `?mode`
Plus: list, complex, special, etc
<img src="https://media.giphy.com/media/ouE6OPO1MADM4/giphy.gif" style="width: 40%" />
???
Before we deep dive into these pieces, we have to make sure we understand types just a little.
While we aren't going to go deep in today, your arguments can be things like lists and dataframes as well as single items - you can get creative!
---
# Arguments, or What Goes In
- Order and naming are important
- Defaults can be set, not required
```{r, echo=TRUE, eval=FALSE}
{{myFunction <- function(a=1, b=1){}}
...
myFunction(a = 2,b = 4)
```
<img src="https://media.giphy.com/media/XhAQgt6ytc6E8/giphy.gif" style="width: 40%" />
???
You can set default values for the arguments as shown
Your arguments need to observe a specific type usually (best practices)
---
class: inverse
# Practice Break 2
Open possible_dog_part2.R and follow the instructions.
- Beginner: Identify the changes in the example function. Try running it, and change the arguments.
- Discuss what change you made and what the effects were. What type/s can the function accept? What happens if you pass something else?
- Advanced: Add an argument to your function, and make it change the output.
```{r, echo=FALSE}
countdown(minutes = 5, seconds = 0, left=0)
```
???
If you weren't comfortable or were not challenged in the group you picked last time, you can switch!
---
# Returns, or What Comes Out
- Object (single) that you'll be able to use elsewhere
- May be any of the types we previously discussed
- Not required! Functions can do things besides return
```{r, echo=TRUE, eval=FALSE}
myFunction <- function(a, b){
...
{{return(c)}}
}
```
<img src="https://media.giphy.com/media/ZaoNH308FHz7a/giphy.gif" style="width: 40%" />
???
Key - make sure the user of this function gets something they are reasonably expecting
A function could change the state of an existing object without using a return (global env, will discuss)
Single object return only in R
---
class: inverse
# Practice Break 3
Open possible_dog_part3.R and follow the instructions.
- Beginner: Identify the changes in the example function. What is it returning?
- Try changing the return, see what it does.
- Advanced: Add a two-element return to your function. Remember that R does not allow multi-argument returns.
```{r, echo=FALSE}
countdown(minutes = 5, seconds = 0, left=0)
```
---
# Guardrails: Documentation
- Explain what the arguments and returns are
- Demonstrate how the function is meant to be used
- May include `@description` or other additional items
```{r, echo=TRUE, eval=FALSE}
#' Explain what my function does
#'
#' @param a Type. Description of what it represents.
#' @param b Type. Description of what it represents.
#'
#' @return Type. Description of what it represents.
#'
#' @examples
#' \dontrun{myFunction(a = 5, b = 3)}
```
<img src="https://media.giphy.com/media/lkdpUMrVSG9D9xiFt0/giphy.gif" style="width: 25%" />
???
Be clear, but not too wordy
Tell the user what they need to know in order to use the function and understand
---
class: inverse
# Practice Break 4
Open possible_dog_part4.R and follow the instructions.
- Beginner: Fill in the blanks in the provided function documentation.
- Advanced: Add documentation for your function, including arguments and returns.
```{r, echo=FALSE}
countdown(minutes = 5, seconds = 0, left=0)
```
---
# Guardrails: Type Check
- Setting an informative error helps the user
- Checks can look at be more than just type
```{r, echo=TRUE, eval=FALSE}
myFunction <- function(a, b){
{{if(!is.double(a)) stop("a must be a number")}}
c <- a*b
return(c)
}
myFunction(a = 2,b = 4)
#myFunction(a = TRUE, b = 4)
```
<img src="https://media.giphy.com/media/zCpYQh5YVhdI1rVYpE/giphy.gif" style="width: 25%" />
???
User might be future you!
---
class: inverse
# Practice Break 5
Open possible_dog_part5.R and follow the instructions.
- Beginner: Examine the type check included in the function. Pass arguments to the function that will violate it.
- Is the error informative?
- Advanced: Add a type check to your function's arguments. Make sure the error message is clear.
```{r, echo=FALSE}
countdown(minutes = 5, seconds = 0, left=0)
```
---
# Guardrails: Tests
- Vital for making packages later
- Helps you ensure that changes have not broken expected behavior
```{r, echo=TRUE, eval=TRUE}
library(testthat)
myFunction <- function(a, b){
if(!is.numeric(a)) stop("a must be a number")
c <- a*b
return(c)
}
```
```{r, echo=TRUE, eval=TRUE}
test_that("Function returns correct value",
{
product = myFunction(a = 2,b = 4)#<<
expect_equal(product, 8)#<<
})
```
???
If the return is not in line with expectations, you can easily find out.
---
# Guardrails: Tests
```{r, echo=TRUE, eval=TRUE}
library(testthat)
test_that("Function returns expected error",
{
{{ expect_error(myFunction(a = TRUE, b = 4))}}
})
```
<img src="https://media.giphy.com/media/LycfkVG4L6x0Y/giphy.gif" style="width: 50%" />
???
Tests can check that it fails or errors when it's supposed to as well!
---
class: inverse
# Practice Break 6
Open possible_dog_part6.R and follow the instructions.
- Beginner: Fill in the argument value that will make the test pass, or change the test.
- Discuss whether it is more sensible to change the argument or the test.
- Advanced: Write a test for your function.
- Do you want to test for expected error or for expected return?
```{r, echo=FALSE}
countdown(minutes = 5, seconds = 0, left=0)
```
---
# Environments
The function knows what exists inside itself, and what exists in the "global" environment.
Outside the function only knows what exists in the "global".
Here, a, b, and c do not exist in the world outside our function.
```{r, echo=TRUE, eval=FALSE}
print(environment())
print(objects())
myFunction <- function(a, b){
{{c <- a*b}}
print(environment())
print(objects())
return(c)
}
myFunction(a = 2,b = 4)
```
---
# Global Environment
- No a, b, or c
```{r, echo=TRUE, eval=TRUE}
print(environment())
print(objects())
```
---
# Function Environment
- Here they are!
```{r, echo=TRUE, eval=TRUE}
myFunction <- function(a, b){
{{c <- a*b}}
print(environment())
print(objects())
return(c)
}
myFunction(a = 2,b = 4)
```
---
# Mixing Environments
```{r, echo=TRUE, eval=TRUE}
myFunction <- function(a, b){
{{d <<- a*b}}
print(environment())
print(objects())
return(d)
}
myFunction(a = 2,b = 4)
print(environment())
print(objects())
```
???
Watch out how you use the double arrow!
---
# Exploring a Function
- Just omit the parentheses
```{r, echo=TRUE, eval=TRUE}
dplyr::top_n
```
---
# Combining Functions
- A function can be an argument to another function
- This way you can chain together elements powerfully
- Helps readability to use functions!
```{r, echo=TRUE, eval=TRUE}
a <- sum(1, 5, 3)
b <- max(a, 4)
b
c <- max(sum(1, 5, 3), 4)
c
```
---
# Conclusion
- Functions are a way of packaging small sections of code to reuse later
- Functions accept input and return output, and contain code
- Documentation and internal tests make functions more useful and easier to work with
<img src="https://media.giphy.com/media/f7rDDvcOV9n8I/giphy.gif" style="width: 50%" />
`r icon::fontawesome("link")` [www.stephaniekirmer.com](http://www.stephaniekirmer.com) | `r icon::fontawesome("twitter")` @[data_stephanie](http://www.twitter.com/data_stephanie)
---
# Further Reading
* http://adv-r.had.co.nz/Functions.html
* https://r4ds.had.co.nz/functions.html
* https://nicercode.github.io/guides/functions/
* https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Writing-your-own-functions
* https://r-pkgs.org/man.html