如何导入sf打包成运行一个依赖lwgeom的函数?

How to import sf to package to run a function that depends on lwgeom?

我正在构建一个导入 {sf} 的包,更具体地说,我在我的一个函数中使用了 st_length()

我最初只将 {sf} 添加到我的包“导入”中,但是当我检查它时,我遇到了一些 {lwgeom} 相关的错误:

Running examples in 'gtfstools-Ex.R' failed
   The error most likely occurred in:
   
   > base::assign(".ptime", proc.time(), pos = "CheckExEnv")
   > ### Name: get_trip_speed
   > ### Title: Get trip speed
   > ### Aliases: get_trip_speed
   > 
   > ### ** Examples
   > 
   > data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools")
   > 
   > gtfs <- read_gtfs(data_path)
   > 
   > trip_speed <- get_trip_speed(gtfs)
   Error in sf::st_length(trips_geometries) : 
     package lwgeom required, please install it first

当示例为 运行 时会出现此错误,但测试会出现一些类似的错误。

然后我将 {lwgeom} 添加到导入。支票运行良好,但最后我收到一条注释:NOTE: Namespaces in Imports field not imported from: 'lwgeom'

处理此类情况的最佳做法是什么?我是否应该跟踪此注释并将其作为评论在包裹提交过程中发送给 CRAN?

您可以考虑在包描述文件的建议字段中添加 {lwgeom} 包。它应该可以解决问题。

可能对这种情况有用的 Suggests != Depends article by Dirk Eddelbuettel refers to a relevant bit of Writing R Extensions (WRE)。

Section 1.1.3.1 (suggested packages) 读取(截至 2021-03-12):

Note that someone wanting to run the examples/tests/vignettes may not have a suggested package available (and it may not even be possible to install it for that platform). The recommendation used to be to make their use conditional via if(require("pkgname")): this is OK if that conditioning is done in examples/tests/vignettes, although using if(requireNamespace("pkgname")) is preferred, if possible.

However, using require for conditioning in package code is not good practice as it alters the search path for the rest of the session and relies on functions in that package not being masked by other require or library calls. It is better practice to use code like

   if (requireNamespace("rgl", quietly = TRUE)) {
      rgl::plot3d(...)
   } else {
      ## do something else not involving rgl.
   }

因此,虽然只是将 {lwgeom} 添加到 Suggests 工作 ,但我们可能会偶然发现有人 运行 是“精简安装”的问题“(即没有建议的包)我的包将无法使用依赖于 {lwgeom} 的功能。

更重要的是,如果我正在导入的包的作者决定 运行 在我的包上进行反向依赖检查而不安装建议的包,检查将失败,因为我有几个例子,测试和小插图位由于没有 {lwgeom} 可用而失败。

因此,除了在 Suggests 中列出它之外,我还添加了一些示例和插图的检查,如 WRE 所建议的:

*examples/vignette context*

# the examples below require the 'lwgeom' package to be installed
if (requireNamespace("lwgeom", quietly = TRUE)) {

  ... do something ...

}

在需要{lwgeom}的函数中我添加了:

if (!requireNamespace("lwgeom", quietly = TRUE))
    stop(
      "The 'lwgeom' package is required to run this function. ",
      "Please install it first."
    )

并将此位添加到此类函数的测试中(使用{testthat}):

if (!requireNamespace("lwgeom", quietly = TRUE)) {

  expect_error(
    set_trip_speed(gtfs, "CPTM L07-0", 50),
    regexp = paste0(
      "The \'lwgeom\' package is required to run this function\. ",
      "Please install it first\."
    )
  )

  skip("'lwgeom' package required to run set_trip_speed() tests.")

}