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

落花浮王杯 提交于 2019-12-22 03:40:51

问题


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?


回答1:


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




回答2:


Just for those late to the party, in the newer versions of roxygen (=> 3.0), the @export tag will work automatically how to deal with methods.

From the Generating Rd files vignette:

S3 generics are regular functions, so document them as such. S3 classes have no formal definition, so document the constructor function. It is your choice whether or not to document S3 methods. You don’t need to document methods for simple generics like print(). If your method is more complicated, you should document it so people know what the parameters do. In base R, you can find documentation for more complex methods like predict.lm(), predict.glm(), and anova.glm().

Older versions of roxygen required explicit @method generic class tags for all S3 methods. From 3.0.0 this is no longer needed as and roxygen2 will figure it out automatically. If you are upgrading, make sure to remove these old tags. Automatic method detection will only fail if the generic and class are ambiguous. For example is all.equal.data.frame() the equal.data.frame method for all, or the data.frame method for all.equal?. If this happens, you can disambiguate with (e.g.) @method all.equal data.frame.



来源:https://stackoverflow.com/questions/18512528/how-to-export-s3-method-so-it-is-available-in-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!