r - 命名空间中的 S3 方法未导出

标签 r namespaces devtools

我正在开发一个 R 包,使用 devtools::document() 来创建 NAMESPACE 文件。其中几个函数是用于汇总、预测、绘图、打印的 S3 方法,其中通用函数位于 basestats 中。 我按照 Hadley 的建议使用 @export,这会导致命名空间中出现正确的 S3method 条目,并且该包通过了所有检查 -as-cran。然而,这些函数没有在命名空间中导出,因此找不到调用 print.myclass (我知道这是避免困惑命名空间的期望行为)。但是,通过 Mypackage::print.myclass 调用该函数也会导致错误,表明该函数不是从 Mypackage 导出的对象。

问题:这是正确的行为吗?或者还需要其他步骤来导出该函数吗?我尝试添加 @method print Myclass 和 @export 但没有成功。在 MAC OS X 10.12.6 下使用 R 3.4.2 和 devtools 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 中的方法分派(dispatch),. 之后的后缀应始终代表您应该作为函数的第一个参数放入的对象类。也就是说,在这种情况下,如果您想通过一次 print 调用来使用 print.hello,则必须放置一个 hello 类code>,成功构建并加载测试包后尝试下面的示例

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 

关于r - 命名空间中的 S3 方法未导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46966169/

相关文章:

r - 有什么方法可以保留包含文本的总行数吗?

r - 避免使用 devtools 检查 R 包构建的示例

r - 无法在 RStudio 中安装 devtools -- 找不到依赖项 (xml2/rversions)

javascript - 范围和命名空间问题

ruby-on-rails - Rails - 如何在 View 中引用命名空间表属性

r - 在我创建的 R 数据包中找不到数据集

r - 按组和列的加权均值

c++ - RcppArmadillo faSTLm 结果与 R 的 lm 不同,我做错了什么?

r - 如何使用 ggplot2 将点和线叠加到等值线图上?

c# - System.Runtime.CompilerServices 的这种使用、不使用或滥用可能有什么值(value)(或危险)?