Exercise 1

Problem

  1. Use function sloop::ftype() to see which of the following functions are S3 generics: mean, summary, print, sum, plot, View, length, [.

  2. Choose 2 of the S3 generics you identified above. How many methods exist for each? Use function sloop::s3_methods_generic().

  3. How many methods exist for classes factor and data.frame. Use function sloop::s3_methods_class().

  4. Consider a class called accounting. If a numeric vector has this class, function print() should print the vector with a $ in front of each number and display values up to two decimals. Create a method for this class.

Solution

Part 1

library(sloop)

Checking a couple of the functions:

ftype(mean)
#> [1] "S3"      "generic"
ftype(plot)
#> [1] "S3"      "generic"

Part 2

nrow(s3_methods_generic("mean"))
#> [1] 6
nrow(s3_methods_generic("plot"))
#> [1] 29

Part 3

nrow(s3_methods_class("factor"))
#> [1] 27
nrow(s3_methods_class("data.frame"))
#> [1] 49

Part 4

print.accounting <- function(x) {
  print(paste0("$", format(round(x, digits = 2), nsmall = 2)), quote = FALSE)
}
x <- 1:5
class(x) <- "accounting"
print(x)
#> [1] $1.00 $2.00 $3.00 $4.00 $5.00
y <- c(4.292, 134.1133, 50.111)
class(y) <- "accounting"
print(y)
#> [1] $  4.29 $134.11 $ 50.11