从 R 中的另一个包扩展 S3 类的正确方法是什么

问题描述 投票:0回答:1

我正在编写一个 R 包

pkgA
,它正在扩展另一个包
pkgB
。特别是,我实现了一个新类
gas_planet
,它扩展了用
planet
编写的类
pkgB
的功能。当我使用
devtools::load_all()
时,将通用函数
pkgB::hello()
扩展到
hello.gas_planet()
没有任何问题。但是,运行
devtools::check()
时,从
pkgB
调用通用函数的示例会停止并出现以下错误:

> checking examples ... ERROR
  Running examples in 'pkgA-Ex.R' failed
  The error most likely occurred in:
  
  > base::assign(".ptime", proc.time(), pos = "CheckExEnv")
  > ### Name: hello.gas_planet
  > ### Title: Say hello to a gas planet
  > ### Aliases: hello.gas_planet
  > 
  > ### ** Examples
  > 
  > planet <- set_gas_planet("Jupiter")
  > hello(planet)
Error in hello(planet) : could not find function "hello"
Execution halted

来自母包

pkgB
的代码是:

#' Set planet
#'
#' @param name planet name
#'
#' @return planet object
#' @export
set_planet <- function(name){
  planet <- list(name = name)
  class(planet) <- "planet"
  return(planet)
}


#' Say hello to a planet
#'
#' @param planet a planet object
#' @param ... More arguments
#'
#' @export
hello <- function(planet, ...) {
  UseMethod("hello", planet)
}

使用命名空间

# Generated by roxygen2: do not edit by hand

export(hello)
export(set_planet)

我的孩子包裹

pkgA
包含代码:

#' Set gas planet
#'
#' @inheritParams pkgB::set_planet
#'
#' @return planet object
#' @export
set_gas_planet <- function(name){
  planet <- list(name = name, structure = "rocky")
  class(planet) <- c("gas_planet", "planet")
  return(planet)
}

#' Say hello to a gas planet
#'
#' @inheritParams pkgB::hello
#'
#' @import pkgB
#'
#' @examples
#' planet <- set_gas_planet("Jupiter")
#' hello(planet)
#'
#' @export
hello.gas_planet <- function(planet, ...) {
  print(paste0("Hello, ", planet$name, "! You look breezy today."))
}

带有命名空间文件

# Generated by roxygen2: do not edit by hand

S3method(hello,gas_planet)
export(set_gas_planet)
import(pkgB)

这篇文章,我了解到不需要

@importFrom
。无论如何,从
@import pkgB
切换到
@importFrom pkgB
并没有解决问题。

阅读上述帖子后我想到的解决方案是在

@export hello
的规范中在
@export
下方添加
hello.gas_planet()
。这使得错误消息消失,但相反,我收到警告:

> checking for missing documentation entries ... WARNING
  Undocumented code objects:
    'hello'
  All user-level objects in a package should have documentation entries.
  See chapter 'Writing R documentation files' in the 'Writing R
  Extensions' manual.

在我看来,为另一个包中的通用函数编写文档是不必要的,而且可能是危险的冗余。从另一个包继承 S3 泛型而不出现任何问题的正确方法是什么?

编辑:

为了重现错误,我为

devtools::check()

pkgA
 创建了两个 GitHub 存储库。我分别使用 R 4.3.1 和 4.3.3 在 Windows 10 和 Windows 11 上产生了错误。我在本地安装了这两个软件包。使用 
pkgB
或使用
devtools::check()
安装软件包后会出现此错误。使用
devtools::install()
后运行示例效果很好。
    

r r-package r-s3
1个回答
0
投票
devtools::load_all()

文件中将母包调用为

Imports
导致的。将
DESCRIPTION
更改为
Imports:
后,
Depends:
devtools::install()
都可以正常工作。更正后的
devtools::check()
文件内容如下:
DESCRIPTION

© www.soinside.com 2019 - 2024. All rights reserved.