I have written code that very simply creates an S3 class for a package. I seek to create a new S3 class so that I can develop, e.g., custom print()
methods.
I have tested the code in a simple R script, but as soon as the function is wrapped into a package, the functionality breaks and the S3 class is no longer created. I cannot provide reproducible code for the creation of the package, but a simplified version of the function I would like to build into the package is introduced below.
My code works perfectly when written either raw or within a function.
x <- 1:10
class(x)
class(x) <- append(class(x),"newS3class")
class(x)
will return c("integer", "newS3class")
Likewise, now, declare a function that does the same thing. This also works fine. In reality, my function foo()
first performs some action on the input, and then returns the output with a new class.
foo <- function(y) {
y <- y + 3
class(y) <- append(class(y), "newS3class")
y
}
class(1:5)
returns "integer"
. class(foo(1:5))
returns c("integer", "newS3class")
. This is as expected.
But, when I develop a package, e.g., mypkg
, and then run mypkg::foo()
, the functionality is broken. I.e., (mypkg::foo(1:5))
returns "integer" rather than c("integer", "newS3class")
.
Is something happening regarding scoping, in the process of building the package from its constituent functions, that is preventing this from working?
The mistake I made here was that I did not properly export the class. To fix this I added the following codeblock, including the export line, before using the roxygen package to build my documentation and NAMESPACE.
#' @export summary.objectclass
makeobjectclass <- function(x) {
class(x) <- c("objectclass", class(x))
x
}