-
Notifications
You must be signed in to change notification settings - Fork 0
/
Function-factories.Rmd
471 lines (332 loc) · 10.4 KB
/
Function-factories.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
# Function factories
```{r Function-factories-1, include = FALSE}
source("common.R")
```
Attaching the needed libraries:
```{r Function-factories-2, warning=FALSE, message=FALSE}
library(rlang, warn.conflicts = FALSE)
library(ggplot2, warn.conflicts = FALSE)
```
## Factory fundamentals (Exercises 10.2.6)
---
**Q1.** The definition of `force()` is simple:
```{r Function-factories-3}
force
```
Why is it better to `force(x)` instead of just `x`?
**A1.** Due to lazy evaluation, argument to a function won't be evaluated until its value is needed. But sometimes we may want to have eager evaluation, and using `force()` makes this intent clearer.
---
**Q2.** Base R contains two function factories, `approxfun()` and `ecdf()`. Read their documentation and experiment to figure out what the functions do and what they return.
**A2.** About the two function factories-
- `approxfun()`
This function factory returns a function performing the linear (or constant) interpolation.
```{r Function-factories-4}
x <- 1:10
y <- rnorm(10)
f <- approxfun(x, y)
f
f(x)
curve(f(x), 0, 11)
```
- `ecdf()`
This function factory computes an empirical cumulative distribution function.
```{r Function-factories-5}
x <- rnorm(12)
f <- ecdf(x)
f
f(seq(-2, 2, by = 0.1))
```
---
**Q3.** Create a function `pick()` that takes an index, `i`, as an argument and returns a function with an argument `x` that subsets `x` with `i`.
```{r Function-factories-6, eval = FALSE}
pick(1)(x)
# should be equivalent to
x[[1]]
lapply(mtcars, pick(5))
# should be equivalent to
lapply(mtcars, function(x) x[[5]])
```
**A3.** To write desired function, we just need to make sure that the argument `i` is eagerly evaluated.
```{r Function-factories-7}
pick <- function(i) {
force(i)
function(x) x[[i]]
}
```
Testing it with specified test cases:
```{r Function-factories-8}
x <- list("a", "b", "c")
identical(x[[1]], pick(1)(x))
identical(
lapply(mtcars, pick(5)),
lapply(mtcars, function(x) x[[5]])
)
```
---
**Q4.** Create a function that creates functions that compute the i^th^ [central moment](http://en.wikipedia.org/wiki/Central_moment) of a numeric vector. You can test it by running the following code:
```{r Function-factories-9, eval = FALSE}
m1 <- moment(1)
m2 <- moment(2)
x <- runif(100)
stopifnot(all.equal(m1(x), 0))
stopifnot(all.equal(m2(x), var(x) * 99 / 100))
```
**A4.** The following function satisfied the specified requirements:
```{r Function-factories-10}
moment <- function(k) {
force(k)
function(x) (sum((x - mean(x))^k)) / length(x)
}
```
Testing it with specified test cases:
```{r Function-factories-11}
m1 <- moment(1)
m2 <- moment(2)
x <- runif(100)
stopifnot(all.equal(m1(x), 0))
stopifnot(all.equal(m2(x), var(x) * 99 / 100))
```
---
**Q5.** What happens if you don't use a closure? Make predictions, then verify with the code below.
```{r Function-factories-12}
i <- 0
new_counter2 <- function() {
i <<- i + 1
i
}
```
**A5.** In case closures are not used in this context, the counts are stored in a global variable, which can be modified by other processes or even deleted.
```{r Function-factories-13}
new_counter2()
new_counter2()
new_counter2()
i <- 20
new_counter2()
```
---
**Q6.** What happens if you use `<-` instead of `<<-`? Make predictions, then verify with the code below.
```{r Function-factories-14}
new_counter3 <- function() {
i <- 0
function() {
i <- i + 1
i
}
}
```
**A6.** In this case, the function will always return `1`.
```{r Function-factories-15}
new_counter3()
new_counter3()
```
---
## Graphical factories (Exercises 10.3.4)
---
**Q1.** Compare and contrast `ggplot2::label_bquote()` with `scales::number_format()`.
**A1.** To compare and contrast, let's first look at the source code for these functions:
- `ggplot2::label_bquote()`
```{r Function-factories-16}
ggplot2::label_bquote
```
- `scales::number_format()`
```{r Function-factories-17}
scales::number_format
```
Both of these functions return formatting functions used to style the facets labels and other labels to have the desired format in `{ggplot2}` plots.
For example, using plotmath expression in the facet label:
```{r Function-factories-18}
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
geom_point()
p + facet_grid(. ~ vs, labeller = label_bquote(cols = alpha^.(vs)))
```
Or to display axes labels in the desired format:
```{r Function-factories-19}
library(scales)
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
scale_y_continuous(labels = number_format(accuracy = 0.01, decimal.mark = ","))
```
The `ggplot2::label_bquote()` adds an additional class to the returned function.
The `scales::number_format()` function is a simple pass-through method that forces evaluation of all its parameters and passes them on to the underlying `scales::number()` function.
---
## Statistical factories (Exercises 10.4.4)
---
**Q1.** In `boot_model()`, why don't I need to force the evaluation of `df` or `model`?
**A1.** We don’t need to force the evaluation of `df` or `model` because these arguments are automatically evaluated by `lm()`:
```{r Function-factories-20}
boot_model <- function(df, formula) {
mod <- lm(formula, data = df)
fitted <- unname(fitted(mod))
resid <- unname(resid(mod))
rm(mod)
function() {
fitted + sample(resid)
}
}
```
---
**Q2.** Why might you formulate the Box-Cox transformation like this?
```{r Function-factories-21}
boxcox3 <- function(x) {
function(lambda) {
if (lambda == 0) {
log(x)
} else {
(x^lambda - 1) / lambda
}
}
}
```
**A2.** To see why we formulate this transformation like above, we can compare it to the one mentioned in the book:
```{r Function-factories-22}
boxcox2 <- function(lambda) {
if (lambda == 0) {
function(x) log(x)
} else {
function(x) (x^lambda - 1) / lambda
}
}
```
Let's have a look at one example with each:
```{r Function-factories-23}
boxcox2(1)
boxcox3(mtcars$wt)
```
As can be seen:
- in `boxcox2()`, we can vary `x` for the same value of `lambda`, while
- in `boxcox3()`, we can vary `lambda` for the same vector.
Thus, `boxcox3()` can be handy while exploring different transformations across inputs.
---
**Q3.** Why don't you need to worry that `boot_permute()` stores a copy of the data inside the function that it generates?
**A3.** If we look at the source code generated by the function factory, we notice that the exact data frame (`mtcars`) is not referenced:
```{r Function-factories-24}
boot_permute <- function(df, var) {
n <- nrow(df)
force(var)
function() {
col <- df[[var]]
col[sample(n, replace = TRUE)]
}
}
boot_permute(mtcars, "mpg")
```
This is why we don't need to worry about a copy being made because the `df` in the function environment points to the memory address of the data frame. We can confirm this by comparing their memory addresses:
```{r Function-factories-25}
boot_permute_env <- rlang::fn_env(boot_permute(mtcars, "mpg"))
rlang::env_print(boot_permute_env)
identical(
lobstr::obj_addr(boot_permute_env$df),
lobstr::obj_addr(mtcars)
)
```
We can also check that the values of these bindings are the same as what we entered into the function factory:
```{r Function-factories-26}
identical(boot_permute_env$df, mtcars)
identical(boot_permute_env$var, "mpg")
```
---
**Q4.** How much time does `ll_poisson2()` save compared to `ll_poisson1()`? Use `bench::mark()` to see how much faster the optimisation occurs. How does changing the length of `x` change the results?
**A4.** Let's first compare the performance of these functions with the example in the book:
```{r Function-factories-27}
ll_poisson1 <- function(x) {
n <- length(x)
function(lambda) {
log(lambda) * sum(x) - n * lambda - sum(lfactorial(x))
}
}
ll_poisson2 <- function(x) {
n <- length(x)
sum_x <- sum(x)
c <- sum(lfactorial(x))
function(lambda) {
log(lambda) * sum_x - n * lambda - c
}
}
x1 <- c(41, 30, 31, 38, 29, 24, 30, 29, 31, 38)
bench::mark(
"LL1" = optimise(ll_poisson1(x1), c(0, 100), maximum = TRUE),
"LL2" = optimise(ll_poisson2(x1), c(0, 100), maximum = TRUE)
)
```
As can be seen, the second version is much faster than the first version.
We can also vary the length of the vector and confirm that across a wide range of vector lengths, this performance advantage is observed.
```{r Function-factories-28}
generate_ll_benches <- function(n) {
x_vec <- sample.int(n, n)
bench::mark(
"LL1" = optimise(ll_poisson1(x_vec), c(0, 100), maximum = TRUE),
"LL2" = optimise(ll_poisson2(x_vec), c(0, 100), maximum = TRUE)
)[1:4] %>%
dplyr::mutate(length = n, .before = expression)
}
(df_bench <- purrr::map_dfr(
.x = c(10, 20, 50, 100, 1000),
.f = ~ generate_ll_benches(n = .x)
))
ggplot(
df_bench,
aes(
x = as.numeric(length),
y = median,
group = as.character(expression),
color = as.character(expression)
)
) +
geom_point() +
geom_line() +
labs(
x = "Vector length",
y = "Median Execution Time",
colour = "Function used"
)
```
---
## Function factories + functionals (Exercises 10.5.1)
**Q1.** Which of the following commands is equivalent to `with(x, f(z))`?
(a) `x$f(x$z)`.
(b) `f(x$z)`.
(c) `x$f(z)`.
(d) `f(z)`.
(e) It depends.
**A1.** It depends on whether `with()` is used with a data frame or a list.
```{r Function-factories-29}
f <- mean
z <- 1
x <- list(f = mean, z = 1)
identical(with(x, f(z)), x$f(x$z))
identical(with(x, f(z)), f(x$z))
identical(with(x, f(z)), x$f(z))
identical(with(x, f(z)), f(z))
```
---
**Q2.** Compare and contrast the effects of `env_bind()` vs. `attach()` for the following code.
**A2.** Let's compare and contrast the effects of `env_bind()` vs. `attach()`.
- `attach()` adds `funs` to the search path. Since these functions have the same names as functions in `{base}` package, the attached names mask the ones in the `{base}` package.
```{r Function-factories-30}
funs <- list(
mean = function(x) mean(x, na.rm = TRUE),
sum = function(x) sum(x, na.rm = TRUE)
)
attach(funs)
mean
head(search())
mean <- function(x) stop("Hi!")
mean
head(search())
detach(funs)
```
- `env_bind()` adds the functions in `funs` to the global environment, instead of masking the names in the `{base}` package.
```{r Function-factories-31}
env_bind(globalenv(), !!!funs)
mean
mean <- function(x) stop("Hi!")
mean
env_unbind(globalenv(), names(funs))
```
Note that there is no `"funs"` in this output.
---
## Session information
```{r Function-factories-32}
sessioninfo::session_info(include_base = TRUE)
```