Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

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

I am creating a package and for S3 methods I export them using

##' @method predict myclass
##' @export
predict.myclass <- function(object,...) { }

Now when I load the package, then predict works on object of the class myclass, but function predict.myclass is not exported. In the NAMESPACE I only get the entry S3method(predict,myclass). So is there a way to export predict.myclass too, so that user will get the code of predict.myclass when he(she) writes predict.myclass in the console?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
")
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...