So I'm working on an R package that use S3 classes, and it would be really nice if I could use sample
as method for one of my classes. However, base
already declares sample
as a non-S3 function, so what I wonder is:
Is it bad style to redefine a non-S3 base
function such as sample
as an S3 function? And could this mess things up for users of my package?
A way you could redefine sample
and still keep the base
function working is:
sample.default <- base::sample
sample <- function(x, ...) {
UseMethod("sample")
}
# This allows me to define a new sample method for my_special_class
sample.my_special_class <- function(...) {...}
But what I'm uncertain about is whether this will cause any trouble or namespace issues, for example, when loading other packages. I've also noticed that not many packages redefine sample
, for example, dplyr uses sample_n
and igraph uses sample_
, and I thought that there might be some reason for this...