Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 189

Hint – Naming conventions

Оглавление

Do not use the dot “.” in function names because it makes them look like S3 functional methods. This might lead to confusion with the convention that the methods are named as <<generic function>>.<<class name>>. Especially, if there is more than one dot in the name. For example, print.data.frame() is not univocal: is it a dataframe method for the generic function print or is it the frame method for the generic function print.data? Another example is the existence of the function t.test() to run t-tests as well as t.dataframe(), that is the S3 method for the generic function t() to transpose a data frame.

t.test()

t.data.frame()

t()

To access the source code of the class-specific methods, one can use the function getS3method().

getS3method()

getS3method(“print”,“table”) ## function (x, digits = getOption(“digits”), quote = FALSE, na.print = “”, ## zero.print = “0”, justify = “none”, …) ## { ## d <- dim(x) ## if (any(d == 0)) { ## cat(“< table of extent”, paste(d, collapse = “ x “), ## “>\n”) ## return(invisible(x)) ## } ## xx <- format(unclass(x), digits = digits, justify = justify) ## if (any(ina <- is.na(x))) ## xx[ina] <- na.print ## if (zero.print != “0” && any(i0 <- !ina & x == 0)) ## xx[i0] <- zero.print ## if (is.numeric(x) || is.complex(x)) ## print(xx, quote = quote, right = TRUE, …) ## else print(xx, quote = quote, …) ## invisible(x) ## } ## <bytecode: 0x5634250f12e8> ## <environment: namespace:base>

The other way around it is possible to list all generic functions that have a specific method for a given class.

You can also list all generics that have a method for a given class:

methods(class = “data.frame”) ## [1] [ [[ [[<- ## [4] [<- $ $<- ## [7] aggregate anyDuplicated as.data.frame ## [10] as.list as.matrix by ## [13] cbind coerce dim ## [16] dimnames dimnames<- droplevels ## [19] duplicated edit format ## [22] formula head initialize ## [25] is.na Math merge ## [28] na.exclude na.omit Ops ## [31] plot print prompt ## [34] rbind row.names row.names<- ## [37] rowsum show slotsFromS3 ## [40] split split<- stack ## [43] str subset summary ## [46] Summary t tail ## [49] transform unique unstack ## [52] within ## see ‘?methods’ for accessing help and source code

The Big R-Book

Подняться наверх