Use function sloop::ftype()
to see which of the following functions are S3 generics: mean
, summary
, print
, sum
, plot
, View
, length
, [
.
Choose 2 of the S3 generics you identified above. How many methods exist for each? Use function sloop::s3_methods_generic()
.
How many methods exist for classes factor
and data.frame
. Use function sloop::s3_methods_class()
.
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.
library(sloop)
Checking a couple of the functions:
ftype(mean)
#> [1] "S3" "generic"
ftype(plot)
#> [1] "S3" "generic"
nrow(s3_methods_generic("mean"))
#> [1] 6
nrow(s3_methods_generic("plot"))
#> [1] 29
nrow(s3_methods_class("factor"))
#> [1] 27
nrow(s3_methods_class("data.frame"))
#> [1] 49
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