幸运的是,对于 R >= 3.6.0,您甚至不需要caldwellst 的答案。从您在上面链接的博客条目中:
从 R 3.6.0 开始,NAMESPACE 中的 S3method() 指令也可用于执行延迟的 S3 方法注册。使用 S3method(PKG::GEN, CLS, FUN) 函数,只有在加载 PKG 的命名空间时,FUN 才会从包 PKG 中注册为 CLS 类和通用 GEN 的 S3 方法。这可以用于处理不“立即”需要该方法的情况,并且必须预加载 pkg 的命名空间(及其所有强依赖项)以执行立即注册被认为过于“昂贵”。
此外,这也在文档中讨论了其他建议vctrs::s3_register()
:
#' For R 3.5.0 and later, `s3_register()` is also useful when demonstrating
#' class creation in a vignette, since method lookup no longer always involves
#' the lexical scope. For R 3.6.0 and later, you can achieve a similar effect
#' by using "delayed method registration", i.e. placing the following in your
#' `NAMESPACE` file:
#'
#' ```
#' if (getRversion() >= "3.6.0") {
#' S3method(package::generic, class)
#' }
因此,您只需要不使用and@importFrom
而不是@export
, 使用@exportS3Method package::generic
(参见https://github.com/r-lib/roxygen2/issues/796和https://github.com/r-lib/roxygen2/commit/ 843432ddc05bc2dabc9b5b22c1ae7de507a00508 )
插图
因此,为了说明,我们可以制作两个非常简单的包,foo
并且bar
. 该包foo
只有一个通用foo()
函数和默认方法:
library(devtools)
create_package("foo")
#' foo generic
#'
#' @param x An object
#' @param ... Arguments passed to or from other methods
#' @export
foo <- function(x, ...) {
UseMethod("foo", x)
}
#' foo default method
#'
#' @param x An object
#' @param ... Arguments passed to or from other methods
#' @export
foo.default <- function(x, ...) {
print("Called default method for foo.")
}
之后document()
,install()
我们创建bar
:
create_package("bar")
它创建了一个bar
方法foo()
:
#' bar method for foo
#'
#' @param x A bar object
#' @param ... Arguments passed to or from other methods
#'
#' @exportS3Method foo::foo
foo.bar <- function(x, ...) {
print("Called bar method for foo.")
}
重要的是,我们必须 在运行之前加载foo
包document()
,否则@exportS3Method
将无法工作。那是,
library(foo)
document()
但是,如果我们这样做,我们会在NAMESPACE
for中得到以下内容bar
:
# Generated by roxygen2: do not edit by hand
S3method(foo::foo,bar)
我们必须手动添加foo
到“建议”中DESCRIPTION
。
然后如果我们卸载foo
,我们仍然可以安装bar
:
> remove.packages("foo")
Removing package from ‘/home/duckmayr/R/x86_64-pc-linux-gnu-library/4.0’
(as ‘lib’ is unspecified)
> install("bar")
✓ checking for file ‘/home/jb/bar/DESCRIPTION’ ...
─ preparing ‘bar’:
✓ checking DESCRIPTION meta-information ...
─ checking for LF line-endings in source and make files and shell scripts
─ checking for empty or unneeded directories
─ building ‘bar_0.0.0.9000.tar.gz’
Running /opt/R/4.0.0/lib/R/bin/R CMD INSTALL \
/tmp/Rtmp5Xgwqf/bar_0.0.0.9000.tar.gz --install-tests
* installing to library ‘/home/jb/R/x86_64-pc-linux-gnu-library/4.0’
* installing *source* package ‘bar’ ...
** using staged installation
** R
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
* DONE (bar)