我正在开发一个R
使用 devtools::document() 进行打包以创建 NAMESPACE 文件。其中几个函数是用于汇总、预测、绘图、打印的 S3 方法,其中通用函数位于base
or stats
。
我按照 Hadley 的建议使用 @export,这会导致命名空间中出现正确的 S3method 条目,并且该包通过了所有检查 -as-cran。然而,这些函数没有在命名空间中导出,因此找不到调用 print.myclass (我知道这是避免混乱命名空间的期望行为)。但是,通过 Mypackage::print.myclass 调用该函数也会导致错误,该函数不是从中导出的对象Mypackage
.
问题:这是正确的行为吗?或者还需要其他步骤来导出该函数吗?我尝试添加 @method print Myclass 和 @export 但没有成功。使用 R 3.4.2 与devtools
MAC OS X 10.12.6 下的 1.13.3
谢谢!梅尔利斯
编辑:更新为添加/导出方法和导出功能的代码
简单的例子 - 在 RStudio 中使用函数构建一个骨架包:
#' test for export of S3 methods
#'
#' @title "print hello world for any object"
#' @param x object
#' @param digits optional number specifying the number of digits to display
#' @param ... other parameters to be passed to \code{print.default}
#' @export print.hello
#' @export
print.hello = function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\n Hello World \n")
invisible()
}
命名空间现在有
# Generated by roxygen2: do not edit by hand
S3method(print,hello)
export(print.hello)
使用不带参数的 @export 会导出该方法,而 @export print.hello 会导出该函数,但不会将该方法添加到命名空间(这将导致包检查出错)。两者兼具就可以导出方法和函数。
首先,为了正式定义 S3 方法并正确导出它,而无需手动更改命名空间文件(假设您使用的是 roxygen),
#' test for export of S3 methods
#'
#' @title "print hello world for any object"
#' @param x object
#' @param digits optional number specifying the number of digits to display
#' @param ... other parameters to be passed to \code{print.default}
#'
#' @rdname print
#' @export print
print <- function(x, ...){
UseMethod("print")
}
#' @rdname print
#' @export print.hello
#' @export
print.hello <- function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\n Hello World \n")
invisible()
}
这或多或少为您提供了预期的行为testPackage::print.hello
。这里更重要的是了解 S3 方法到底是做什么用的。用于R中的方法调度以及后面的后缀.
应该始终代表您应该作为函数第一个参数放入的对象类。也就是说,在这种情况下,如果你想使用print.hello
通过一次调用print
,你必须放一类hello
,在成功构建并加载测试包后尝试下面的示例
a = 1
print(a) # method dispatched as print.default because class of a is numeric
# 1
class(a) <- 'hello'
print(a) # method dispatched as print.hello
# Hello World
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)