只为一个函数加载依赖

Load dependencies only for one function

我正在创建一个包含一些功能的包。只有一个辅助功能需要plotly

然而,当我使用 devtools 安装时,我收到一条注释 unused arguments in layout(yaxis = ay,... 然后我阅读 Hadley's article about imports vs depends。使用 import 不会删除注释,但在 NAMESPACE 文件中添加 plotlydepends 可以解决问题。

接下来我阅读了关于 'Search Path' 的段落。 Hadley 在这里指出

You should never use require() or library() in a package: instead, use the Depends or Imports fields in the DESCRIPTION

我现在的问题是,使用 plotly 的函数更像是一个附加组件。所有其他(更重要的)功能都适用于 base-R。 因此,我只想将 plotly 用于需要它的一个函数。

  1. 是否可以在 install 期间不创建笔记?
  2. 为什么 requirelibrary 在包内如此糟糕?
  3. 可以先使用 requireNamespace 然后再使用 require 吗?

下面是一些示例代码:

#' Some plotly function
#'
#' Some very long description
#'
#' @param x_vec A numeric vector
#' @param y_vec A numeric vector
#' @keywords Some keywords
#' @return A plotly object
#' @export
#' @examples

debugMinEx<-function(x_vec,y_vec){

ay <- list(title = "",zeroline = FALSE,showline = FALSE,
           showticklabels = FALSE, showgrid = FALSE,
           scaleanchor="x",scaleratio=1) ## empty axis
ax <- list(title = "",zeroline = FALSE,showline = FALSE,
           showticklabels = FALSE, showgrid = FALSE) ## empty axis
my_legend<-list(font = list(family = "sans-serif", size = 14, color = "#000000"),
                x = 0, y = -0.05,orientation = "h")

plot_ly() %>%
  add_trace(x=x_vec,y=y_vec,
            type='scatter',mode='lines') %>%
  layout(yaxis = ay,xaxis=ax,
          legend = my_legend)
}

为此使用建议

您可以在 Writing R Extensions or in Hadley's Package Basics: Decription 中阅读它。在这两种情况下,建议是

  • 可选依赖项位于包 DESCRIPTIONSuggests 字段中。
  • 在函数中使用if (requireNamespace)来测试包是否存在。

像这样:

if (requireNamespace("plotly", quietly = TRUE)) {
      # do your plotly stuff
   } else {
      # do non-plotly stuff
      # maybe as simple as stop("Please install plotly to use this function")
   }

至于在requireNamespace之后是否可以使用require——这似乎毫无意义。 Hadley 的建议似乎很明确,可以使用 requireNamespace("plotly") 加载包,然后使用 plotly:: 调用所需的函数。

如果您不想理会此建议,那么第一次 require 就可以了。使用 requireNamespace 后跟 require 是多余的。正如您在 link 中所解释的,requireNamespace 加载了一个包而不附加它。 require 加载和附加。