Export error on overwriting primitives with S3 in R package

谁说我不能喝 提交于 2021-01-27 12:21:22

问题


I'm trying to create a S3 method in my package called dimnames. This is a primitive in R, but there should be an S3 in my package with the same name.

I've got the following file dimnames.r

#' S3 overwriting primitive
#'
#' @param x  object
#' @export
dimnames = function(x) {
    UseMethod("dimnames")
}

#' title
#'
#' @export
dimnames.data.frame = function(x) {
    dimnames.default(x)
}

#' title
#'
#' @export
dimnames.list = function(x) {
    lapply(x, dimnames)
}

#' title
#'
#' @export
dimnames.default = function(x) {
    message("in S3 method")
    base::dimnames(x)
}

I then create a package from it (in R=3.3.2):

> package.skeleton("rpkg", code_files="dimnames.r")
> setwd("rpkg")
> devtools::document() # version 1.12.0

And then check the package

R CMD build rpkg
R CMD check rpkg_1.0.tar.gz

I get the following output (among other messages):

Warning: declared S3 method 'dimnames.default' not found

Warning: declared S3 method 'dimnames.list' not found

Loading the package and checking its contents, dimnames.data.frame is exported while dimnames.default and dimnames.list are not. This does not make sense to me. As far as I understand, I declared the exports correctly. Also, the NAMESPACE file looks good to me:

S3method(dimnames,data.frame)
S3method(dimnames,default)
S3method(dimnames,list)
export(dimnames)

Why does this not work, and how to fix it?

(Bonus points for: why do I need #' title in the S3 implementations when they should not be needed with roxygen=5.0.1?)


回答1:


S3 methods are only exported if it is desired that the user be able to access them directly. If they are always to be invoked via the generic then there is no need to export them.

The problem with R CMD check is likely due to defining your own generic for dimnames. Normally one just defines methods and leverages off the primitive generic already in R. Remove the dimnames generic from dimnames.r.

There should be no problem in adding methods for new classes but you may have problems trying to override the functionality of dimnames for existing classes that R's dimnames handles itself.



来源:https://stackoverflow.com/questions/40873221/export-error-on-overwriting-primitives-with-s3-in-r-package

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