How to export S3 method so it is available in namespace?

Solution 1:

If you would like to have both an S3method and export directive in your NAMESPACE in an automated way with roxygen2, you can simply add an extra @export tag that is more explicit.

To illustrate, I created a dummy package, exportTest. This package has only one file in the R/ subdirectory, print.foo.R:

#' Print method for "foo" class
#'
#' @param x An object of class "foo"
#' @param ... Other arguments passed to or from other methods
#'
#' @export print.foo
#' @export
print.foo <- function(x, ...) {
    cat("This is just a dummy function.\n")
}

After document()ing, I have the following NAMESPACE:

# Generated by roxygen2: do not edit by hand

S3method(print,foo)
export(print.foo)

I got this idea from Hadley's advice on exporting a non-S3-method function with a . in the name. If you use

#' @export function.name

it explicitly uses an export() directive for certain with the provided function.name. Then I tested whether you could combine it with a more ambiguous @export tag to also generate an S3method() directive, and voila! It works.

However, I will note that to my knowledge, being able to do this for certain isn't documented anywhere, so it's possible to stop working at some point, perhaps even without warning. If this is functionality that you want to ensure exists and/or have documented somewhere, I would suggest opening an issue at their GitHub repo.

Solution 2:

My answer is "don't do that". The user can methods(predict); getAnywhere('predict.myclass') or mypackage:::predict.myclass. There's a learning curve for the user, but mastering this with your method helps the user navigate all methods. Reasons not to export the method are that it isn't meant to be invoked directly, and it clutters the search path with unnecessary symbols (every symbol typed at the prompt, e.g., ls(), has to be found by looking through objects on all environments returned by search(), and user packages like yours stand between the start of the search and name resolution of these commonly used functions).