问题
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