load/remove 包装上的用户定义单位 load/unload:最佳实践?

load/remove user-defined unit on package load/unload: best practise?

在我正在开发的包中,我需要定义一个新单位:相当于 100 英尺的飞行高度 (FL)。

units包提供了以下可能性:

units::install_conversion_constant("FL", "ft", 100)

为了使包测试 (devtools::test()) 和包检查 (devtools::test()) 都适用于我使用此用户定义单元的单元测试,我需要 I discovered在包加载阶段注册它。

这是我所做的:

zzz.R 中(根据 "When you do need side-effects" 部分的新文件):

# register flight levels (FL) as a unit when loading this package
.onLoad <- function(libname, pkgname) {
  # install user-define unit for flight level
  units::install_conversion_constant("FL", "ft", 100)

  invisible()
}

# register flight levels (FL) as a unit when loading this package
.onUnload <- function(libname, pkgname) {
  # uninstall user-define unit for flight level
  units::remove_symbolic_unit("FL")

  invisible()
}

如果不这样做,将单元注册码放入某些 R/unit-conversion.R 文件中,则 devtools::test() 成功,但 devtools::check() 失败。

上面的解决方案是否是注册(删除[这也应该这样做?])包中新单元的正确方法吗?

这几乎绝对是为您的包裹做这件事的地方。我说几乎是因为每条规则都有例外。阅读下面的部分以了解更多详细信息和基本 R 手册中的最佳实践推荐

https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-hooks.html

Good practice Loading a namespace should where possible be silent, with startup messages given by .onAttach. These messages (and any essential ones from .onLoad) should use packageStartupMessage so they can be silenced where they would be a distraction.

There should be no calls to library nor require in these hooks. The way for a package to load other packages is via the Depends field in the ‘DESCRIPTION’ file: this ensures that the dependence is documented and packages are loaded in the correct order. Loading a namespace should not change the search path, so rather than attach a package, dependence of a namespace on another package should be achieved by (selectively) importing from the other package's namespace.

Uses of library with argument help to display basic information about the package should use format on the computed package information object and pass this to packageStartupMessage.

There should be no calls to installed.packages in startup code: it is potentially very slow and may fail in versions of R before 2.14.2 if package installation is going on in parallel. See its help page for alternatives.

Compiled code should be loaded (e.g., via library.dynam) in .onLoad or a useDynLib directive in the ‘NAMESPACE’ file, and not in .onAttach. Similarly, compiled code should not be unloaded (e.g., via library.dynam.unload) in .Last.lib nor .onDetach, only in .onUnload.