简体   繁体   English

如何在使用roxygen2时指定加载S4方法的顺序

[英]How to specify in which order to load S4 methods when using roxygen2

I ran into following problem already multiple times. 我已多次遇到以下问题。

Say you have two classes, classA and classB described in the following files classA.R : 假设您有两个类, classAclassB在以下文件中描述classA.R

#' the class classA
#'
#' This is a class A blabla
#' \section{Slots}{\describe{\item{\code{A}}{a Character}}}
#' @ name classA
#' @rdname classA
#' @exportClass classA
setClass("classA",representation(A="character"))

And classB.R classB.R

#' the class classB
#'
#' This is a class B blabla
#' \section{Slots}{\describe{\item{\code{B}}{an object of class A}}}
#' @ name classB
#' @rdname classB
#' @exportClass classB
setClass("classB",representation(B="classA"))

I believed these files were read in alphabetical order by roxygen2 , but that is not the case. 我相信这些文件是由roxygen2按字母顺序roxygen2 ,但事实并非如此。 If I try to build the package, I might get the following error: 如果我尝试构建包,我可能会收到以下错误:

roxygenize("./myExample")
Error in getClass(Class, where = topenv(parent.frame())) :
   "ClassA" is not a defined class

How can I make sure that roxygenize() knows in which order to read the files, ie which class definition should be read before the other? 我怎样才能确保roxygenize()知道读取文件的顺序,即哪个类定义应该在另一个之前读取?


Note : I know I answered my own question. 注意:我知道我回答了自己的问题。 That is because I ran into this problem rather often, and realized the proper way to do this after looking at the code of roxygen2 . 那是因为我经常遇到这个问题,并在查看roxygen2的代码后意识到了这样做的正确方法。 So for reference, here's my findings. 所以作为参考,这是我的发现。

There are two ways to achieve this: 有两种方法可以实现这一目标:

As described in ?collate_roclet , you can use the @include tag to specify which class should be read before which. ?collate_roclet ,您可以使用@include标记指定在此之前应该读取的类。 In this case, you can add to the file classB.r the following line right before the actual R code: 在这种情况下,您可以在实际R代码之前的以下行添加到文件classB.r

#' @include classA.r

These tags are read specifically to update the Collate field in the DESCRIPTION file, and are the recommended way of dealing with the problem. 这些标记专门用于更新DESCRIPTION文件中的Collate字段,是处理问题的推荐方法。

In some cases the dependencies might be so complex you want to keep an overview yourself and not rely completely on adding @include tags in your codebase. 在某些情况下,依赖关系可能非常复杂,您希望自己保持概述,而不是完全依赖于在代码库中添加@include标记。 In that case you can just specify the Collate field at the end of the DESCRIPTION file, like this: 在这种情况下,您只需在DESCRIPTION文件的末尾指定Collate字段,如下所示:

Package: myExample
Type: Package
...
Collate:
    'classA.R'
    'classB.R'

The function roxygenize() first checks the DESCRIPTION file, and loads whatever files are specified there first in the order they're specified. 函数roxygenize()首先检查DESCRIPTION文件,然后按照指定的顺序加载首先指定的文件。 Only then the rest of the package is loaded. 只有这样才能加载包的其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM