-
Notifications
You must be signed in to change notification settings - Fork 0
/
Functions.Rmd
868 lines (594 loc) · 21.4 KB
/
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
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# Functions
```{r Functions-1, include = FALSE}
source("common.R")
```
Attaching the needed libraries:
```{r Functions-2, warning=FALSE, message=FALSE}
library(tidyverse, warn.conflicts = FALSE)
```
## Function fundamentals (Exercises 6.2.5)
**Q1.** Given a name, like `"mean"`, `match.fun()` lets you find a function. Given a function, can you find its name? Why doesn't that make sense in R?
**A1.** Given a name, `match.fun()` lets you find a function.
```{r Functions-3}
match.fun("mean")
```
But, given a function, it doesn't make sense to find its name because there can be multiple names bound to the same function.
```{r Functions-4}
f1 <- function(x) mean(x)
f2 <- f1
match.fun("f1")
match.fun("f2")
```
**Q2.** It's possible (although typically not useful) to call an anonymous function. Which of the two approaches below is correct? Why?
```{r Functions-5, result = "hide"}
function(x) 3()
(function(x) 3)()
```
**A2.** The first expression is not correct since the function will evaluate `3()`, which is syntactically not allowed since literals can't be treated like functions.
```{r Functions-6, error=TRUE}
f <- (function(x) 3())
f
f()
rlang::is_syntactic_literal(3)
```
This is the correct way to call an anonymous function.
```{r Functions-7}
g <- (function(x) 3)
g
g()
```
**Q3.** A good rule of thumb is that an anonymous function should fit on one line and shouldn't need to use `{}`. Review your code. Where could you have used an anonymous function instead of a named function? Where should you have used a named function instead of an anonymous function?
**A3.** Self activity.
**Q4.** What function allows you to tell if an object is a function? What function allows you to tell if a function is a primitive function?
**A4.** Use `is.function()` to check if an *object* is a *function*:
```{r Functions-8}
# these are functions
f <- function(x) 3
is.function(mean)
is.function(f)
# these aren't
is.function("x")
is.function(new.env())
```
Use `is.primitive()` to check if a *function* is *primitive*:
```{r Functions-9}
# primitive
is.primitive(sum)
is.primitive(`+`)
# not primitive
is.primitive(mean)
is.primitive(read.csv)
```
**Q5.** This code makes a list of all functions in the base package.
```{r Functions-10, eval = FALSE}
objs <- mget(ls("package:base", all = TRUE), inherits = TRUE)
funs <- Filter(is.function, objs)
```
Use it to answer the following questions:
a. Which base function has the most arguments?
b. How many base functions have no arguments? What's special about those functions?
c. How could you adapt the code to find all primitive functions?
**A5.** The provided code is the following:
```{r Functions-11}
objs <- mget(ls("package:base", all = TRUE), inherits = TRUE)
funs <- Filter(is.function, objs)
```
a. Which base function has the most arguments?
We can use `formals()` to extract number of arguments, but because this function returns `NULL` for primitive functions.
```{r Functions-12}
formals("!")
length(formals("!"))
```
Therefore, we will focus only on non-primitive functions.
```{r Functions-13}
funs <- purrr::discard(funs, is.primitive)
```
`scan()` function has the most arguments.
```{r Functions-14}
df_formals <- purrr::map_df(funs, ~ length(formals(.))) %>%
tidyr::pivot_longer(
cols = dplyr::everything(),
names_to = "function",
values_to = "argumentCount"
) %>%
dplyr::arrange(desc(argumentCount))
df_formals
```
b. How many base functions have no arguments? What’s special about those functions?
```{r Functions-15, echo=FALSE, include=FALSE}
df_formals_0 <- dplyr::filter(df_formals, argumentCount == 0)
```
At the time of writing, `r nrow(df_formals_0)` base (non-primitive) functions have no arguments.
```{r Functions-16}
dplyr::filter(df_formals, argumentCount == 0)
```
c. How could you adapt the code to find all primitive functions?
```{r Functions-17}
objs <- mget(ls("package:base", all = TRUE), inherits = TRUE)
funs <- Filter(is.function, objs)
primitives <- Filter(is.primitive, funs)
length(primitives)
names(primitives)
```
**Q6.** What are the three important components of a function?
**A6.** Except for primitive functions, all functions have 3 important components:
* `formals()`
* `body()`
* `environment()`
**Q7.** When does printing a function not show the environment it was created in?
**A7.** All package functions print their environment:
```{r Functions-18}
# base
mean
# other package function
purrr::map
```
There are two exceptions where the enclosing environment won't be printed:
- primitive functions
```{r Functions-19}
sum
```
- functions created in the global environment
```{r Functions-20}
f <- function(x) mean(x)
f
```
## Lexical scoping (Exercises 6.4.5)
**Q1.** What does the following code return? Why? Describe how each of the three `c`'s is interpreted.
```{r Functions-21, eval = FALSE}
c <- 10
c(c = c)
```
**A1.** In `c(c = c)`:
* first *c* is interpreted as a function call `c()`
* second *c* as a name for the vector element
* third *c* as a variable with value `10`
```{r Functions-22}
c <- 10
c(c = c)
```
You can also see this in the lexical analysis of this expression:
```{r Functions-23}
p_expr <- parse(text = "c(c = c)", keep.source = TRUE)
getParseData(p_expr) %>% select(token, text)
```
**Q2.** What are the four principles that govern how R looks for values?
**A2.** Principles that govern how R looks for values:
1. Name masking (names defined inside a function mask names defined outside a function)
1. Functions vs. variables (the rule above also applies to function names)
1. A fresh start (every time a function is called, a new environment is created to host its execution)
1. Dynamic look-up (R looks for values when the function is run, not when the function is created)
**Q3.** What does the following function return? Make a prediction before running the code yourself.
```{r Functions-24, results = "hide"}
f <- function(x) {
f <- function(x) {
f <- function() {
x^2
}
f() + 1
}
f(x) * 2
}
f(10)
```
**A3.** Correctly predicted 😉
```{r Functions-25}
f <- function(x) {
f <- function(x) {
f <- function() {
x^2
}
f() + 1
}
f(x) * 2
}
f(10)
```
Although there are multiple `f()` functions, the order of evaluation goes from inside to outside with `x^2` evaluated first and `f(x) * 2` evaluated last. This results in `r f(10)` (= `((10 ^ 2) + 1) * 2`).
## Lazy evaluation (Exercises 6.5.4)
**Q1.** What important property of `&&` makes `x_ok()` work?
```{r Functions-26, eval = FALSE}
x_ok <- function(x) {
!is.null(x) && length(x) == 1 && x > 0
}
x_ok(NULL)
x_ok(1)
x_ok(1:3)
```
What is different with this code? Why is this behaviour undesirable here?
```{r Functions-27, eval = FALSE}
x_ok <- function(x) {
!is.null(x) & length(x) == 1 & x > 0
}
x_ok(NULL)
x_ok(1)
x_ok(1:3)
```
**A1.** `&&` evaluates left to right and has short-circuit evaluation, i.e., if the first operand is `TRUE`, R will short-circuit and not even look at the second operand.
```{r Functions-28}
x_ok <- function(x) {
!is.null(x) && length(x) == 1 && x > 0
}
x_ok(NULL)
x_ok(1)
x_ok(1:3)
```
Replacing `&&` with `&` is undesirable because it performs element-wise logical comparisons and returns a vector of values that is not always useful for a decision (`TRUE`, `FALSE`, or `NA`).
```{r Functions-29}
x_ok <- function(x) {
!is.null(x) & length(x) == 1 & x > 0
}
x_ok(NULL)
x_ok(1)
x_ok(1:3)
```
**Q2.** What does this function return? Why? Which principle does it illustrate?
```{r Functions-30, results = "hide"}
f2 <- function(x = z) {
z <- 100
x
}
f2()
```
**A2.** The function returns `100` due to lazy evaluation.
When function execution environment encounters `x`, it evaluates argument `x = z` and since the name `z` is already bound to the value 100 in this environment, `x` is also bound to the same value.
We can check this by looking at the memory addresses:
```{r Functions-31}
f2 <- function(x = z) {
z <- 100
print(lobstr::obj_addrs(list(x, z)))
x
}
f2()
```
**Q3.** What does this function return? Why? Which principle does it illustrate?
```{r Functions-32, results = "hide"}
y <- 10
f1 <- function(x =
{
y <- 1
2
},
y = 0) {
c(x, y)
}
f1()
y
```
**A3.** Let's first look at what the function returns:
```{r Functions-33}
y <- 10
f1 <- function(x =
{
y <- 1
2
},
y = 0) {
c(x, y)
}
f1()
y
```
This is because of name masking. In the function call `c(x, y)`, when `x` is accessed in the function environment, the following promise is evaluated in the function environment:
```{r Functions-34, eval = FALSE}
x <- {
y <- 1
2
}
```
And, thus `y` gets assigned to `1`, and `x` to `2`, since its the last value in that scope.
Therefore, neither the promise `y = 0` nor global assignment `y <- 10` is ever consulted to find the value for `y`.
**Q4.** In `hist()`, the default value of `xlim` is `range(breaks)`, the default value for `breaks` is `"Sturges"`, and
```{r Functions-35}
range("Sturges")
```
Explain how `hist()` works to get a correct `xlim` value.
**A4.** The `xlim` defines the range of the histogram's `x`-axis.
```{r Functions-36}
hist(mtcars$wt, xlim = c(1, 6))
```
The default `xlim = range(breaks)` and `breaks = "Sturges"` arguments reveal that the function uses Sturges' algorithm to compute the number of breaks.
```{r Functions-37}
nclass.Sturges(mtcars$wt)
```
To see the implementation, run `sloop::s3_get_method("hist.default")`.
`hist()` ensures that the chosen algorithm returns a numeric vector containing at least two unique elements before `xlim` is computed.
**Q5.** Explain why this function works. Why is it confusing?
```{r Functions-38}
show_time <- function(x = stop("Error!")) {
stop <- function(...) Sys.time()
print(x)
}
show_time()
```
**A5.** Let's take this step-by-step.
The function argument `x` is missing in the function call. This means that `stop("Error!")` is evaluated in the function environment, and not global environment.
But, due to lazy evaluation, the promise `stop("Error!")` is evaluated only when `x` is accessed. This happens only when `print(x)` is called.
`print(x)` leads to `x` being evaluated, which evaluates `stop` in the function environment. But, in function environment, the `base::stop()` is masked by a locally defined `stop()` function, which returns `Sys.time()` output.
**Q6.** How many arguments are required when calling `library()`?
**A6.** Going solely by its signature,
```{r Functions-39}
formals(library)
```
it looks like the following arguments are required:
```{r Functions-40}
formals(library) %>%
purrr::discard(is.null) %>%
purrr::map_lgl(~ .x == "") %>%
purrr::keep(~ isTRUE(.x)) %>%
names()
```
But, in reality, only one argument is required: `package`. The function internally checks if the other arguments are missing and adjusts accordingly.
It would have been better if there arguments were `NULL` instead of missing; that would avoid this confusion.
## `...` (dot-dot-dot) (Exercises 6.6.1)
**Q1.** Explain the following results:
```{r Functions-41}
sum(1, 2, 3)
mean(1, 2, 3)
sum(1, 2, 3, na.omit = TRUE)
mean(1, 2, 3, na.omit = TRUE)
```
**A1.** Let's look at arguments for these functions:
```{r Functions-42}
str(sum)
str(mean)
```
As can be seen, `sum()` function doesn't have `na.omit` argument. So, the input `na.omit = TRUE` is treated as `1` (logical implicitly coerced to numeric), and thus the results. So, the expression evaluates to `sum(1, 2, 3, 1)`.
For `mean()` function, there is only one parameter (`x`) and it's matched by the first argument (`1`). So, the expression evaluates to `mean(1)`.
**Q2.** Explain how to find the documentation for the named arguments in the following function call:
```{r Functions-43, fig.asp = 1, small_mar = TRUE, fig.width = 3}
plot(1:10, col = "red", pch = 20, xlab = "x", col.lab = "blue")
```
**A2.** Typing `?plot` in the console, we see its documentation, which also shows its signature:
```{r Functions-44, echo=FALSE}
str(plot)
```
Since `...` are passed to `par()`, we can look at `?par` docs:
```{r Functions-45, echo=FALSE}
str(par)
```
And so on.
The docs for all parameters of interest [reside there](https://rdrr.io/r/graphics/par.html).
**Q3.** Why does `plot(1:10, col = "red")` only colour the points, not the axes or labels? Read the source code of `plot.default()` to find out.
**A3.** Source code can be found [here](https://github.com/wch/r-source/blob/79e73dba5259b25ec30118d45fea64aeac0f41dc/src/library/graphics/R/plot.R#L51-L84).
`plot.default()` passes `...` to `localTitle()`, which passes it to `title()`.
`title()` has four parts: `main`, `sub`, `xlab`, `ylab`.
So having a single argument `col` would not work as it will be ambiguous as to which element to apply this argument to.
```{r Functions-46, eval=FALSE}
localTitle <- function(..., col, bg, pch, cex, lty, lwd) title(...)
title <- function(main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
line = NA, outer = FALSE, ...) {
main <- as.graphicsAnnot(main)
sub <- as.graphicsAnnot(sub)
xlab <- as.graphicsAnnot(xlab)
ylab <- as.graphicsAnnot(ylab)
.External.graphics(C_title, main, sub, xlab, ylab, line, outer, ...)
invisible()
}
```
## Exiting a function (Exercises 6.7.5)
**Q1.** What does `load()` return? Why don't you normally see these values?
**A1.** The `load()` function reloads datasets that were saved using the `save()` function:
```{r Functions-47}
save(iris, file = "my_iris.rda")
load("my_iris.rda")
```
We normally don't see any value because the function loads the datasets invisibly.
We can change this by setting `verbose = TRUE`:
```{r Functions-48}
load("my_iris.rda", verbose = TRUE)
# cleanup
unlink("my_iris.rda")
```
**Q2.** What does `write.table()` return? What would be more useful?
**A2.** The `write.table()` writes a data frame to a file and returns a `NULL` invisibly.
```{r Functions-49}
write.table(BOD, file = "BOD.csv")
```
It would have been more helpful if the function invisibly returned the actual object being written to the file, which could then be further used.
```{r Functions-50}
# cleanup
unlink("BOD.csv")
```
**Q3.** How does the `chdir` parameter of `source()` compare to `with_dir()`? Why might you prefer one to the other?
**A3.** The `chdir` parameter of `source()` is described as:
> if `TRUE` and `file` is a pathname, the `R` working directory is temporarily changed to the directory containing file for evaluating
That is, `chdir` allows changing working directory temporarily but *only* to the directory containing file being sourced:
While `withr::with_dir()` temporarily changes the current working directory:
```{r Functions-51}
withr::with_dir
```
More importantly, its parameters `dir` allows temporarily changing working directory to *any* directory.
**Q4.** Write a function that opens a graphics device, runs the supplied code, and closes the graphics device (always, regardless of whether or not the plotting code works).
**A4.** Here is a function that opens a graphics device, runs the supplied code, and closes the graphics device:
```{r Functions-52, eval=FALSE}
with_png_device <- function(filename, code, ...) {
grDevices::png(filename = filename, ...)
on.exit(grDevices::dev.off(), add = TRUE)
force(code)
}
```
**Q5.** We can use `on.exit()` to implement a simple version of `capture.output()`.
```{r Functions-53, eval = getRversion() >= "3.5"}
capture.output2 <- function(code) {
temp <- tempfile()
on.exit(file.remove(temp), add = TRUE, after = TRUE)
sink(temp)
on.exit(sink(), add = TRUE, after = TRUE)
force(code)
readLines(temp)
}
capture.output2(cat("a", "b", "c", sep = "\n"))
```
Compare `capture.output()` to `capture.output2()`. How do the functions differ? What features have I removed to make the key ideas easier to see? How have I rewritten the key ideas so they're easier to understand?
**A5.** The `capture.output()` is significantly more complex, as can be seen by its definition:
```{r Functions-54}
capture.output
```
Here are few key differences:
- `capture.output()` uses `print()` function to print to console:
```{r Functions-55}
capture.output(1)
capture.output2(1)
```
- `capture.output()` can capture messages as well:
```{r Functions-56}
capture.output(message("Hi there!"), "a", type = "message")
```
- `capture.output()` takes into account visibility of the expression:
```{r Functions-57}
capture.output(1, invisible(2), 3)
```
## Function forms (Exercises 6.8.6)
**Q1.** Rewrite the following code snippets into prefix form:
```{r Functions-58, eval = FALSE}
1 + 2 + 3
1 + (2 + 3)
if (length(x) <= 5) x[[5]] else x[[n]]
```
**A1.** Prefix forms for code snippets:
```{r Functions-59, eval=FALSE}
# The binary `+` operator has left to right associative property.
`+`(`+`(1, 2), 3)
`+`(1, `(`(`+`(2, 3)))
`if`(cond = `<=`(length(x), 5), cons.expr = `[[`(x, 5), alt.expr = `[[`(x, n))
```
**Q2.** Clarify the following list of odd function calls:
```{r Functions-60, eval = FALSE}
x <- sample(replace = TRUE, 20, x = c(1:10, NA))
y <- runif(min = 0, max = 1, 20)
cor(m = "k", y = y, u = "p", x = x)
```
**A2.** These functions don't have dots (`...`) as parameters, so the argument matching takes place in the following steps:
- exact matching for named arguments
- partial matching
- position-based
**Q3.** Explain why the following code fails:
```{r Functions-61, eval = FALSE}
modify(get("x"), 1) <- 10
#> Error: target of assignment expands to non-language object
```
**A3.** As provided in the book, the replacement function is defined as:
```{r Functions-62}
`modify<-` <- function(x, position, value) {
x[position] <- value
x
}
```
Let's re-write the provided code in prefix format to understand why it doesn't work:
```{r Functions-63, eval=FALSE}
get("x") <- `modify<-`(x = get("x"), position = 1, value = 10)
```
Although this works:
```{r Functions-64}
x <- 5
`modify<-`(x = get("x"), position = 1, value = 10)
```
The following doesn't because the code above evaluates to:
```{r Functions-65, error=TRUE}
`get<-`("x", 10)
```
And there is no `get<-` function in R.
**Q4.** Create a replacement function that modifies a random location in a vector.
**A4.** A replacement function that modifies a random location in a vector:
```{r Functions-66}
`random_modify<-` <- function(x, value) {
random_index <- sample(seq_along(x), size = 1)
x[random_index] <- value
return(x)
}
```
Let's try it out:
```{r Functions-67}
x1 <- rep("a", 10)
random_modify(x1) <- "X"
x1
x2 <- rep("a", 10)
random_modify(x2) <- "Y"
x2
x3 <- rep(0, 15)
random_modify(x3) <- -4
x3
x4 <- rep(0, 15)
random_modify(x4) <- -1
x4
```
**Q5.** Write your own version of `+` that pastes its inputs together if they are character vectors but behaves as usual otherwise. In other words, make this code work:
```{r Functions-68, eval = FALSE}
1 + 2
#> [1] 3
"a" + "b"
#> [1] "ab"
```
**A5.** Infix operator to re-create the desired output:
```{r Functions-69}
`+` <- function(x, y) {
if (is.character(x) || is.character(y)) {
paste0(x, y)
} else {
base::`+`(x, y)
}
}
1 + 2
"a" + "b"
rm("+", envir = .GlobalEnv)
```
**Q6.** Create a list of all the replacement functions found in the base package. Which ones are primitive functions? (Hint: use `apropos()`.)
**A6.** Replacement functions always have `<-` at the end of their names.
So, using `apropos()`, we can find all replacement functions in search paths and the filter out the ones that don't belong to `{base}` package:
```{r Functions-70}
ls_replacement <- apropos("<-", where = TRUE, mode = "function")
base_index <- which(grepl("base", searchpaths()))
ls_replacement <- ls_replacement[which(names(ls_replacement) == as.character(base_index))]
unname(ls_replacement)
```
The primitive replacement functions can be listed using `is.primitive()`:
```{r Functions-71}
mget(ls_replacement, envir = baseenv()) %>%
purrr::keep(is.primitive) %>%
names()
```
**Q7.** What are valid names for user-created infix functions?
**A7.** As mentioned in the respective [section](https://adv-r.hadley.nz/functions.html#infix-functions) of the book:
> The names of infix functions are more flexible than regular R functions: they can contain any sequence of characters except for `%`.
**Q8.** Create an infix `xor()` operator.
**A8.** Exclusive OR is a logical operation that is `TRUE` if and only if its arguments differ (one is `TRUE`, the other is `FALSE`).
```{r Functions-72}
lv1 <- c(TRUE, FALSE, TRUE, FALSE)
lv2 <- c(TRUE, TRUE, FALSE, FALSE)
xor(lv1, lv2)
```
We can create infix operator for exclusive OR like so:
```{r Functions-73}
`%xor%` <- function(x, y) {
!((x & y) | !(x | y))
}
lv1 %xor% lv2
TRUE %xor% TRUE
```
The function is vectorized over its inputs because the underlying logical operators themselves are vectorized.
**Q9.** Create infix versions of the set functions `intersect()`, `union()`, and `setdiff()`. You might call them `%n%`, `%u%`, and `%/%` to match conventions from mathematics.
**A9.** The required infix operators can be created as following:
```{r Functions-74}
`%n%` <- function(x, y) {
intersect(x, y)
}
`%u%` <- function(x, y) {
union(x, y)
}
`%/%` <- function(x, y) {
setdiff(x, y)
}
```
We can check that the outputs agree with the underlying functions:
```{r Functions-75}
(x <- c(sort(sample(1:20, 9)), NA))
(y <- c(sort(sample(3:23, 7)), NA))
identical(intersect(x, y), x %n% y)
identical(union(x, y), x %u% y)
identical(setdiff(x, y), x %/% y)
```
## Session information
```{r Functions-76}
sessioninfo::session_info(include_base = TRUE)
```