【问题标题】:taking care of dependencies in your functions处理函数中的依赖关系
【发布时间】:2010-05-27 22:36:21
【问题描述】:

如何解决函数中包的依赖关系?我在函数中添加了require(package),但我想知道是否有完成这项任务的首选方式。

【问题讨论】:

    标签: r dependencies


    【解决方案1】:

    根据函数的帮助,require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist

    以后……

    The source code for a package that requires one or more other packages should have a call to require, preferably near the beginning of the source, and of course before any code that uses functions, classes or methods from the other package

    【讨论】:

      【解决方案2】:

      通过使用包的DESCRIPTION 文件的Depends: 字段。

      这也是为什么你更喜欢使用包而不是仅仅使用你是source()-ing 的文件的另一个原因。

      编辑:在DESCRIPTION 中也有Imports:。但总体而言,R 具有 依赖机制,如果使用它会更好。

      【讨论】:

        【解决方案3】:

        标准格式好像是

        if(!require(the_package))
        {
          #Maybe try an alternative or do some cleanup here
          stop("You must install the package 'the_package'.")
        }
        

        如果你的包广泛使用另一个包,那么你应该在你的包初始化时加载那个包,即在.First.lib函数中将它添加到你的包描述文件的Depends字段中。如果包只被你的一个或两个函数使用,那么这段代码就在这些函数的开头。

        【讨论】:

        • 你知道是否有一个函数像 if(!require(the_package)){ install.packages("the_package");需要(the_package)}
        • @Etiennebr:我不这么认为,因为用户可以特别关注自己安装包,而不是让功能偷偷为他们做。
        猜你喜欢
        • 2015-05-11
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-02
        • 1970-01-01
        • 2021-12-14
        相关资源
        最近更新 更多