r - 只为一个函数加载依赖

标签 r plotly devtools roxygen2

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

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

接下来我阅读了有关“搜索路径”的段落。哈德利在这里指出

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. 是否可以在安装 期间不创建注释?
  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 中阅读相关信息或者在 Hadley 的 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 是多余的。如您的链接中所述,requireNamespace 加载包而不附加它。 需要加载和附加。

关于r - 只为一个函数加载依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54131005/

相关文章:

python - 使用时间戳绘制甘特图

Python:ValueError:所有参数都应该具有相同的长度

python - 绘制多个饼图,其位置位于 for 循环中

r - 记录 ggplot2 统计扩展 - devtools::document() 未创建 packagename-ggproto.Rd

string - 剪贴板查看器用于编程目的

python - 使用R的rPython来运行python的rpy2

r - 使用插入符号指定交叉验证折叠

r - 如何让 R 包推荐托管在 GitHub 上的包?

R:在 rgl 的 3D 散点图中向拟合平面添加垂线

r - 轻松检查目标是否记录在其他变量中?