gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:58:41 26 4
gpt4 key购买 nike

我正在创建一个 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() - 完整通话 :: - 所以我列出plyrImports:在我的DESCRIPTION文件。但是,当我使用devtools::check()时我明白了:

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

为什么我会收到此注释?

我可以通过添加@importFrom dplyr ldply来避免这条注释。在使用 plyr 的文件中,但后来我结束了,但有 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 检查

总之,官方的说法是,Hadley 的建议(您引用的)仅适用于很少使用的包(和/或需要花费大量时间来完成的包)中很少使用的函数。加载)。否则,只需像 WRE 建议的那样执行 @importFrom 即可:

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

关于R 与 roxygen2 : How to use a single function from another package?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36574141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com