R with roxygen2:如何使用另一个包中的单个函数?

R with roxygen2: How to use a single function from another package?

我正在创建一个 R 包,它将使用 来自 plyr 的单个函数。根据 this roxygen2 vignette:

If you are using just a few functions from another package, the recommended option is to note the package name in the Imports: field of the DESCRIPTION file and call the function(s) explicitly using ::, e.g., pkg::fun().

听起来不错。我正在使用 plyr::ldply() - :: 的完整调用 - 所以我在 DESCRIPTION 文件的 Imports: 中列出了 plyr。但是,当我使用 devtools::check() 我得到这个:

* checking dependencies in R code ... NOTE
All declared Imports should be used:
  ‘plyr’
  All declared Imports should be used.

为什么我会收到这张便条?

我可以通过在使用 plyr 的文件中添加 @importFrom dplyr ldply 来避免注释,但是我结束时在我的包命名空间中有 ldply。我不想要,也不应该需要,因为我使用 plyr::ldply() 一次我使用该功能。

如有指点,将不胜感激!

This question 可能相关。)

如果 ldply() 对您的包的功能很重要,那么您确实需要它在您的包命名空间中。这就是命名空间导入的意义所在。您需要的函数应该在包命名空间中,因为这是 R 将首先查找函数定义的地方,然后再遍历基本命名空间和附加的包。这意味着无论加载或卸载什么其他包,附加或取消附加,您的包将始终可以访问该功能。在这种情况下,使用:

@importFrom plyr ldply

并且您可以只引用 ldply() 而无需 plyr:: 前缀,就好像它是您包中的另一个函数一样。

如果ldply()不是那么重要——也许它只在一个不常用的函数中被调用一次——那么,Writing R Extensions 1.5.1给出以下建议:

If a package only needs a few objects from another package it can use a fully qualified variable reference in the code instead of a formal import. A fully qualified reference to the function f in package foo is of the form foo::f. This is slightly less efficient than a formal import and also loses the advantage of recording all dependencies in the NAMESPACE file (but they still need to be recorded in the DESCRIPTION file). Evaluating foo::f will cause package foo to be loaded, but not attached, if it was not loaded already—this can be an advantage in delaying the loading of a rarely used package.

(我认为这个建议实际上有点过时,因为它暗示 DESCRIPTIONNAMESPACE 之间的分离比目前存在的更多。)它意味着你应该使用 @import plyr 并参考到 plyr::ldply() 的函数。但实际上,它实际上是在建议将 plyr 放在 DESCRIPTIONSuggests 字段中,这既不完全符合 roxygen2 标记的要求,也不完全符合 R CMD check

总之,官方说法是 Hadley 的建议(您引用的)仅适用于很少使用的包中很少使用的函数(and/or 包需要相当长的时间来加载)。否则,就像 WRE 建议的那样 @importFrom

Using importFrom selectively rather than import is good practice and recommended notably when importing from packages with more than a dozen exports.