-
Notifications
You must be signed in to change notification settings - Fork 0
/
S3.Rmd
1013 lines (709 loc) · 24 KB
/
S3.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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# S3
```{r S3-1, include = FALSE}
source("common.R")
```
Attaching the needed libraries:
```{r, warning=FALSE, message=FALSE}
library(sloop, warn.conflicts = FALSE)
library(dplyr, warn.conflicts = FALSE)
library(purrr, warn.conflicts = FALSE)
```
## Basics (Exercises 13.2.1)
---
**Q1.** Describe the difference between `t.test()` and `t.data.frame()`. When is each function called?
**A1.** The difference between `t.test()` and `t.data.frame()` is the following:
- `t.test()` is a **generic** function to perform a *t*-test.
- `t.data.frame()` is a **method** for generic `t()` (a matrix transform function) and will be dispatched for `data.frame` objects.
We can also confirm these function types using `ftype()`:
```{r S3-2}
ftype(t.test)
ftype(t.data.frame)
```
---
**Q2.** Make a list of commonly used base R functions that contain `.` in their name but are not `S3` methods.
**A2.** Here are a few common R functions with `.` but that are not `S3` methods:
- `all.equal()`
- Most of `as.*` functions (like `as.data.frame()`, `as.numeric()`, etc.)
- `install.packages()`
- `on.exit()`
etc.
<!-- For full list, you could do: -->
<!-- ```{r S3-3, eval=FALSE} -->
<!-- base_functions <- getNamespaceExports("base") -->
<!-- base_functions[grepl("(\\w+)(\\.)(\\w+)", base_functions)] -->
<!-- ``` -->
For example,
```{r S3-4}
ftype(as.data.frame)
ftype(on.exit)
```
---
**Q3.** What does the `as.data.frame.data.frame()` method do? Why is it confusing? How could you avoid this confusion in your own code?
**A3.** It's an `S3` **method** for **generic** `as.data.frame()`.
```{r S3-5}
ftype(as.data.frame.data.frame)
```
It can be seen in all methods supported by this generic:
```{r S3-6}
s3_methods_generic("as.data.frame") %>%
dplyr::filter(class == "data.frame")
```
Given the number of `.`s in this name, it is quite confusing to figure out what is the name of the generic and the name of the class.
---
**Q4.** Describe the difference in behaviour in these two calls.
```{r S3-7}
set.seed(1014)
some_days <- as.Date("2017-01-31") + sample(10, 5)
mean(some_days)
mean(unclass(some_days))
```
**A4.** The difference in behaviour in the specified calls.
- Before unclassing, the `mean` generic dispatches `.Date` method:
```{r S3-8}
some_days <- as.Date("2017-01-31") + sample(10, 5)
some_days
s3_dispatch(mean(some_days))
mean(some_days)
```
- After unclassing, the `mean` generic dispatches `.numeric` method:
```{r S3-9}
unclass(some_days)
mean(unclass(some_days))
s3_dispatch(mean(unclass(some_days)))
```
---
**Q5.** What class of object does the following code return? What base type is it built on? What attributes does it use?
```{r S3-10, eval=FALSE}
x <- ecdf(rpois(100, 10))
x
```
**A5.** The object is based on base type `closure`^[of "object of type 'closure' is not subsettable" fame], which is a type of function.
```{r S3-11}
x <- ecdf(rpois(100, 10))
x
otype(x)
typeof(x)
```
Its class is `ecdf`, which has other superclasses.
```{r S3-12}
s3_class(x)
```
Apart from `class`, it has the following attributes:
```{r S3-13}
attributes(x)
```
---
**Q6.** What class of object does the following code return? What base type is it built on? What attributes does it use?
```{r S3-14, eval = FALSE}
x <- table(rpois(100, 5))
x
```
**A6.** The object is based on base type `integer`.
```{r S3-15}
x <- table(rpois(100, 5))
x
otype(x)
typeof(x)
```
Its class is `table`.
```{r S3-16}
s3_class(x)
```
Apart from `class`, it has the following attributes:
```{r S3-17}
attributes(x)
```
---
## Classes (Exercises 13.3.4)
---
**Q1.** Write a constructor for `data.frame` objects. What base type is a data frame built on? What attributes does it use? What are the restrictions placed on the individual elements? What about the names?
**A1.** A data frame is built on top of a named list of atomic vectors and has attributes for row names:
```{r S3-18}
unclass(data.frame())
```
The restriction imposed on individual elements is that they need to have the same length. Additionally, the names need to be syntactically valid and unique.
```{r S3-19}
new_data_frame <- function(x = list(), row.names = character()) {
# row names should be character
if (!all(is.character(row.names))) {
stop("Row name should be of `chracter` type.", call. = FALSE)
}
# all elements should have the same length
unique_element_lengths <- unique(purrr::map_int(x, length))
if (length(unique_element_lengths) > 1L) {
stop("All list elements in `x` should have same length.", call. = FALSE)
}
# if not provided, generate row names
# this is necessary if there is at least one element in the list
if (length(x) > 0L && length(row.names) == 0L) {
row.names <- .set_row_names(unique_element_lengths)
}
structure(x, class = "data.frame", row.names = row.names)
}
```
Let's try it out:
```{r S3-20, error=TRUE}
new_data_frame(list("x" = 1, "y" = c(2, 3)))
new_data_frame(list("x" = 1, "y" = c(2)), row.names = 1L)
new_data_frame(list())
new_data_frame(list("x" = 1, "y" = 2))
new_data_frame(list("x" = 1, "y" = 2), row.names = "row-1")
```
---
**Q2.** Enhance my `factor()` helper to have better behaviour when one or more `values` is not found in `levels`. What does `base::factor()` do in this situation?
**A2.** When one or more `values` is not found in `levels`, those values are converted to `NA` in `base::factor()`:
```{r S3-21}
base::factor(c("a", "b", "c"), levels = c("a", "c"))
```
In the new constructor, we can throw an error to inform the user:
```{r S3-22}
new_factor <- function(x = integer(), levels = character()) {
stopifnot(is.integer(x))
stopifnot(is.character(levels))
structure(
x,
levels = levels,
class = "factor"
)
}
validate_factor <- function(x) {
values <- unclass(x)
levels <- attr(x, "levels")
if (!all(!is.na(values) & values > 0)) {
stop(
"All `x` values must be non-missing and greater than zero",
call. = FALSE
)
}
if (length(levels) < max(values)) {
stop(
"There must be at least as many `levels` as possible values in `x`",
call. = FALSE
)
}
x
}
create_factor <- function(x = character(), levels = unique(x)) {
ind <- match(x, levels)
if (any(is.na(ind))) {
missing_values <- x[which(is.na(match(x, levels)))]
stop(
paste0(
"Following values from `x` are not present in `levels`:\n",
paste0(missing_values, collapse = "\n")
),
call. = FALSE
)
}
validate_factor(new_factor(ind, levels))
}
```
Let's try it out:
```{r S3-23, error=TRUE}
create_factor(c("a", "b", "c"), levels = c("a", "c"))
create_factor(c("a", "b", "c"), levels = c("a", "b", "c"))
```
---
**Q3.** Carefully read the source code of `factor()`. What does it do that my constructor does not?
**A3.** The source code for `factor()` can be read [here](https://github.com/r-devel/r-svn/blob/master/src/library/base/R/factor.R).
There are a number ways in which the base version is more flexible.
- It allows labeling the values:
```{r S3-24}
x <- c("a", "b", "b")
levels <- c("a", "b", "c")
labels <- c("one", "two", "three")
factor(x, levels = levels, labels = labels)
```
- It checks that the levels are not duplicated.
```{r S3-25, error=TRUE}
x <- c("a", "b", "b")
levels <- c("a", "b", "b")
factor(x, levels = levels)
create_factor(x, levels = levels)
```
- The `levels` argument can be `NULL`.
```{r S3-26, error=TRUE}
x <- c("a", "b", "b")
factor(x, levels = NULL)
create_factor(x, levels = NULL)
```
**Q4.** Factors have an optional "contrasts" attribute. Read the help for `C()`, and briefly describe the purpose of the attribute. What type should it have? Rewrite the `new_factor()` constructor to include this attribute.
**A4.** Categorical variables are typically encoded as dummy variables in regression models and by default each level is compared with the first factor level. Contrats provide a flexible way for such comparisons.
You can set the `"contrasts"` attribute for a factor using `stats::C()`.
Alternatively, you can set the `"contrasts"` attribute using matrix (`?contrasts`):
> [Contrasts] can be a matrix with one row for each level of the factor or a suitable function like contr.poly or a character string giving the name of the function
The constructor provided in the book:
```{r S3-27}
new_factor <- function(x = integer(), levels = character()) {
stopifnot(is.integer(x))
stopifnot(is.character(levels))
structure(
x,
levels = levels,
class = "factor"
)
}
```
Here is how it can be updated to also support contrasts:
```{r S3-28}
new_factor <- function(x = integer(),
levels = character(),
contrasts = NULL) {
stopifnot(is.integer(x))
stopifnot(is.character(levels))
if (!is.null(contrasts)) {
stopifnot(is.matrix(contrasts) && is.numeric(contrasts))
}
structure(
x,
levels = levels,
class = "factor",
contrasts = contrasts
)
}
```
**Q5.** Read the documentation for `utils::as.roman()`. How would you write a constructor for this class? Does it need a validator? What might a helper do?
**A5.** `utils::as.roman()` converts Indo-Arabic numerals to Roman numerals. Removing its class also reveals that it is implemented using the base type `integer`:
```{r S3-29}
as.roman(1)
typeof(unclass(as.roman(1)))
```
Therefore, we can create a simple constructor to create a new instance of this class:
```{r S3-30}
new_roman <- function(x = integer()) {
stopifnot(is.integer(x))
structure(x, class = "roman")
}
```
The docs mention the following:
> Only numbers between 1 and 3899 have a unique representation as roman numbers, and hence others result in as.roman(NA).
```{r S3-31}
as.roman(10000)
```
Therefore, we can warn the user and then return `NA` in a validator function:
```{r S3-32}
validate_new_roman <- function(x) {
int_values <- unclass(x)
if (any(int_values < 1L | int_values > 3899L)) {
warning(
"Integer should be between 1 and 3899. Returning `NA` otherwise.",
call. = FALSE
)
}
x
}
```
The helper function can coerce the entered input to integer type for convenience:
```{r S3-33}
roman <- function(x = integer()) {
x <- as.integer(x)
validate_new_roman(new_roman(x))
}
```
Let's try it out:
```{r S3-34}
roman(1)
roman(c(5, 20, 100, 150, 100000))
```
## Generics and methods (Exercises 13.4.4)
**Q1.** Read the source code for `t()` and `t.test()` and confirm that `t.test()` is an S3 generic and not an S3 method. What happens if you create an object with class `test` and call `t()` with it? Why?
```{r S3-35, results = FALSE}
x <- structure(1:10, class = "test")
t(x)
```
**A1.** Looking at source code of these functions, we can see that both of these are generic, and we can confirm the same using `{sloop}`:
```{r S3-36}
t
sloop::is_s3_generic("t")
t.test
sloop::is_s3_generic("t.test")
```
Looking at the `S3` dispatch, we can see that since R can't find `S3` method for `test` class for generic function `t()`, it dispatches the default method, which converts the structure to a matrix:
```{r S3-37}
x <- structure(1:10, class = "test")
t(x)
s3_dispatch(t(x))
```
The same behaviour can be observed with a vector:
```{r S3-38}
t(1:10)
```
**Q2.** What generics does the `table` class have methods for?
**A2.** The `table` class have methods for the following generics:
```{r S3-39}
s3_methods_class("table")
```
**Q3.** What generics does the `ecdf` class have methods for?
**A3.** The `ecdf` class have methods for the following generics:
```{r S3-40}
s3_methods_class("ecdf")
```
**Q4.** Which base generic has the greatest number of defined methods?
**A4.** To answer this question, first, let's list all functions base has and only retain the generics.
```{r S3-41}
# getting all functions names
objs <- mget(ls("package:base", all = TRUE), inherits = TRUE)
funs <- Filter(is.function, objs)
# extracting only generics
genFuns <- names(funs) %>%
purrr::keep(~ sloop::is_s3_generic(.x))
```
Now it's a simple matter of counting number of methods per generic and ordering the data frame in descending order of this count:
```{r S3-42}
purrr::map_dfr(
genFuns,
~ s3_methods_generic(.)
) %>%
dplyr::group_by(generic) %>%
dplyr::tally() %>%
dplyr::arrange(desc(n))
```
This reveals that the base generic function with most methods is `print()`.
**Q5.** Carefully read the documentation for `UseMethod()` and explain why the following code returns the results that it does. What two usual rules of function evaluation does `UseMethod()` violate?
```{r S3-43}
g <- function(x) {
x <- 10
y <- 10
UseMethod("g")
}
g.default <- function(x) c(x = x, y = y)
x <- 1
y <- 1
g(x)
```
**A5.** If called directly, `g.default()` method takes `x` value from argument and `y` from the global environment:
```{r}
g.default(x)
```
But, if `g()` function is called, it takes the `x` from argument, but comes from function environment:
```{r}
g(x)
```
The docs for `?UseMethod()` clarify why this is the case:
> Any local variables defined before the call to UseMethod are retained
That is, when `UseMethod()` calls `g.default()`, variables defined inside the generic are also available to `g.default()` method. The arguments supplied to the function are passed on as is, however, and cannot be affected by code inside the generic.
Two rules of function evaluation violated by `UseMethod()`:
- Name masking
- A fresh start
**Q6.** What are the arguments to `[`? Why is this a hard question to answer?
**A6.** It is difficult to say how many formal arguments the subsetting `[` operator has because it is a generic function with methods for vectors, matrices, arrays, lists, etc., and these different methods have different number of arguments:
```{r S3-44}
s3_methods_generic("[") %>%
dplyr::filter(source == "base")
```
We can sample a few of them to see the wide variation in the number of formal arguments:
```{r S3-45}
# table
names(formals(`[.table`))
# Date
names(formals(`[.Date`))
# data frame
names(formals(`[.data.frame`))
# etc.
```
## Object styles (Exercises 13.5.1)
**Q1.** Categorise the objects returned by `lm()`, `factor()`, `table()`, `as.Date()`, `as.POSIXct()` `ecdf()`, `ordered()`, `I()` into the styles described above.
**A1.** Objects returned by these functions can be categorized as follows:
- Vector style objects (`length` represents no. of observations)
`factor()`
```{r S3-46}
factor_obj <- factor(c("a", "b"))
length(factor_obj)
length(unclass(factor_obj))
```
`table()`
```{r S3-47}
tab_object <- table(mtcars$am)
length(tab_object)
length(unlist(tab_object))
```
`as.Date()`
```{r S3-48}
date_obj <- as.Date("02/27/92", "%m/%d/%y")
length(date_obj)
length(unclass(date_obj))
```
`as.POSIXct()`
```{r S3-49}
posix_obj <- as.POSIXct(1472562988, origin = "1960-01-01")
length(posix_obj)
length(unclass(posix_obj))
```
`ordered()`
```{r S3-50}
ordered_obj <- ordered(factor(c("a", "b")))
length(ordered_obj)
length(unclass(ordered_obj))
```
- Record style objects (equi-length vectors to represent object components)
None.
- Dataframe style objects (Record style but two-dimensions)
None.
- Scalar objects (a list to represent a single thing)
`lm()` (represent one regression model)
```{r S3-51}
lm_obj <- lm(wt ~ mpg, mtcars)
length(lm_obj)
length(unclass(lm_obj))
```
`ecdf()` (represents one distribution)
```{r S3-52}
ecdf_obj <- ecdf(rnorm(12))
length(ecdf_obj)
length(unclass(ecdf_obj))
```
`I()` is special:
It just adds a new class to the object to indicate that it should be treated *as is*.
```{r S3-53}
x <- ecdf(rnorm(12))
class(x)
class(I(x))
```
Therefore, the object style would be the same as the superclass' object style.
**Q2.** What would a constructor function for `lm` objects, `new_lm()`, look like? Use `?lm` and experimentation to figure out the required fields and their types.
**A2.** The `lm` object is a scalar object, i.e. this object contains a named list of atomic vectors of varying lengths and types to represent a single thing (a regression model).
```{r S3-54}
mod <- lm(wt ~ mpg, mtcars)
typeof(mod)
attributes(mod)
purrr::map_chr(unclass(mod), typeof)
purrr::map_int(unclass(mod), length)
```
Based on this information, we can write a new constructor for this object:
```{r S3-55}
new_lm <- function(coefficients,
residuals,
effects,
rank,
fitted.values,
assign,
qr,
df.residual,
xlevels,
call,
terms,
model) {
stopifnot(
is.double(coefficients),
is.double(residuals),
is.double(effects),
is.integer(rank),
is.double(fitted.values),
is.integer(assign),
is.list(qr),
is.integer(df.residual),
is.list(xlevels),
is.language(call),
is.language(terms),
is.list(model)
)
structure(
list(
coefficients = coefficients,
residuals = residuals,
effects = effects,
rank = rank,
fitted.values = fitted.values,
assign = assign,
qr = qr,
df.residual = df.residual,
xlevels = xlevels,
call = call,
terms = terms,
model = model
),
class = "lm"
)
}
```
## Inheritance (Exercises 13.6.3)
**Q1.** How does `[.Date` support subclasses? How does it fail to support subclasses?
**A1.** The `[.Date` method is defined as follows:
```{r S3-56}
sloop::s3_get_method("[.Date")
```
The `.Date` function looks like this:
```{r S3-57}
.Date
```
Here, `oldClass` is the same as `class()`.
Therefore, by reading this code, we can surmise that:
- `[.Date` supports subclasses by preserving the class of the input.
- `[.Date` fails to support subclasses by not preserving the attributes of the input.
For example,
```{r S3-58}
x <- structure(Sys.Date(), name = "myName", class = c("subDate", "Date"))
# `$name` is gone
attributes(x[1])
x[1]
```
**Q2.** R has two classes for representing date time data, `POSIXct` and `POSIXlt`, which both inherit from `POSIXt`. Which generics have different behaviours for the two classes? Which generics share the same behaviour?
**A2.** First, let's demonstrate that `POSIXct` and `POSIXlt` are indeed subclasses and `POSIXt` is the superclass.
```{r S3-59}
dt_lt <- as.POSIXlt(Sys.time(), "GMT")
class(dt_lt)
dt_ct <- as.POSIXct(Sys.time(), "GMT")
class(dt_ct)
dt_t <- structure(dt_ct, class = "POSIXt")
class(dt_t)
```
Remember that the way `S3` method dispatch works, if a generic has a method for superclass, then that method is also inherited by the subclass.
We can extract a vector of all generics supported by both sub- and super-classes:
```{r S3-60}
(t_generics <- s3_methods_class("POSIXt")$generic)
(lt_generics <- s3_methods_class("POSIXlt")$generic)
(ct_generics <- s3_methods_class("POSIXct")$generic)
```
Methods which are specific to the subclasses:
```{r S3-61}
union(lt_generics, ct_generics)
```
Let's see an example:
```{r S3-62}
s3_dispatch(is.na(dt_lt))
s3_dispatch(is.na(dt_ct))
s3_dispatch(is.na(dt_t))
```
Methods which are inherited by subclasses from superclass:
```{r S3-63}
setdiff(t_generics, union(lt_generics, ct_generics))
```
Let's see one example generic:
```{r S3-64}
s3_dispatch(is.numeric(dt_lt))
s3_dispatch(is.numeric(dt_ct))
s3_dispatch(is.numeric(dt_t))
```
**Q3.** What do you expect this code to return? What does it actually return? Why?
```{r S3-65, eval = FALSE}
generic2 <- function(x) UseMethod("generic2")
generic2.a1 <- function(x) "a1"
generic2.a2 <- function(x) "a2"
generic2.b <- function(x) {
class(x) <- "a1"
NextMethod()
}
generic2(structure(list(), class = c("b", "a2")))
```
**A3.** Naively, we would expect for this code to return `"a1"`, but it actually returns `"a2"`:
```{r S3-66}
generic2 <- function(x) UseMethod("generic2")
generic2.a1 <- function(x) "a1"
generic2.a2 <- function(x) "a2"
generic2.b <- function(x) {
class(x) <- "a1"
NextMethod()
}
generic2(structure(list(), class = c("b", "a2")))
```
`S3` dispatch explains why:
```{r S3-67}
sloop::s3_dispatch(generic2(structure(list(), class = c("b", "a2"))))
```
As mentioned in the book, the `UseMethod()` function
> tracks the list of potential next methods with a special variable, which means that modifying the object that’s being dispatched upon will have no impact on which method gets called next.
This special variable is `.Class`:
> `.Class` is a character vector of classes used to find the next method. `NextMethod` adds an attribute "previous" to `.Class` giving the `.Class` last used for dispatch, and shifts `.Class` along to that used for dispatch.
So, we can print `.Class` to confirm that adding a new class to `x` indeed doesn't change `.Class`, and therefore dispatch occurs on `"a2"` class:
```{r S3-68}
generic2.b <- function(x) {
message(paste0("before: ", paste0(.Class, collapse = ", ")))
class(x) <- "a1"
message(paste0("after: ", paste0(.Class, collapse = ", ")))
NextMethod()
}
invisible(generic2(structure(list(), class = c("b", "a2"))))
```
## Dispatch details (Exercises 13.7.5)
**Q1.** Explain the differences in dispatch below:
```{r S3-69}
length.integer <- function(x) 10
x1 <- 1:5
class(x1)
s3_dispatch(length(x1))
x2 <- structure(x1, class = "integer")
class(x2)
s3_dispatch(length(x2))
```
**A1.** The differences in the dispatch are due to classes of arguments:
```{r S3-70}
s3_class(x1)
s3_class(x2)
```
`x1` has an implicit class `integer` but it inherits from `numeric`, while `x2` is explicitly assigned the class `integer`.
**Q2.** What classes have a method for the `Math` group generic in base R? Read the source code. How do the methods work?
**A2.** The following classes have a method for the `Math` group generic in base R:
```{r S3-71}
s3_methods_generic("Math") %>%
dplyr::filter(source == "base")
```
Reading source code for a few of the methods:
[`Math.factor()`](https://github.com/r-devel/r-svn/blob/master/src/library/base/R/factor.R) and [`Math.Date()`](https://github.com/r-devel/r-svn/blob/master/src/library/base/R/dates.R) provide only error message:
```{r S3-72, eval=FALSE}
Math.factor <- function(x, ...) {
stop(gettextf("%s not meaningful for factors", sQuote(.Generic)))
}
Math.Date <- function(x, ...) {
stop(gettextf("%s not defined for \"Date\" objects", .Generic),
domain = NA
)
}
```
[`Math.data.frame()`](https://github.com/r-devel/r-svn/blob/master/src/library/base/R/factor.R) is defined as follows (except the first line of code, which I have deliberately added):
```{r S3-73}
Math.data.frame <- function(x, ...) {
message(paste0("Environment variable `.Generic` set to: ", .Generic))
mode.ok <- vapply(x, function(x) {
is.numeric(x) || is.logical(x) || is.complex(x)
}, NA)
if (all(mode.ok)) {
x[] <- lapply(X = x, FUN = .Generic, ...)
return(x)
} else {
vnames <- names(x)
if (is.null(vnames)) vnames <- seq_along(x)
stop(
"non-numeric-alike variable(s) in data frame: ",
paste(vnames[!mode.ok], collapse = ", ")
)
}
}
```
As can be surmised from the code: the method checks that all elements are of the same and expected type.
If so, it applies the generic (tracked via the environment variable `.Generic`) to each element of the list of atomic vectors that makes up a data frame:
```{r S3-74}
df1 <- data.frame(x = 1:2, y = 3:4)
sqrt(df1)
```
If not, it produces an error:
```{r S3-75, error=TRUE}
df2 <- data.frame(x = c(TRUE, FALSE), y = c("a", "b"))
abs(df2)
```
**Q3.** `Math.difftime()` is more complicated than I described. Why?
**A3.** [`Math.difftime()`](https://github.com/r-devel/r-svn/blob/master/src/library/base/R/datetime.R) source code looks like the following:
```{r S3-76}
Math.difftime <- function(x, ...) {
switch(.Generic,
"abs" = ,
"sign" = ,
"floor" = ,
"ceiling" = ,
"trunc" = ,
"round" = ,
"signif" = {
units <- attr(x, "units")
.difftime(NextMethod(), units)
},
### otherwise :
stop(gettextf("'%s' not defined for \"difftime\" objects", .Generic),
domain = NA