首页 > 解决方案 > 将 Reduce() 与导入包中的函数列表一起使用

问题描述

我目前正在尝试创建一个包,并且一直在遵循 Hadley Wickham 的建议,方法是调用命名空间而不是 Roxygen 中的 @import 包名。

我有这个功能:

make_plot <- function(data, x, y, groups = NULL, error.params = list(),
                      graph.params = list(), ...) {

  ggplot(data, aes(x, y, colour = groups)) +
    build_bar_graph(error.params, graph.params) +
    build_graph_options(...)

}

那叫

build_graph_options <- function(...) {
  Reduce("+", list(...), accumulate = TRUE)
}

其中...应该是,例如,xlab()、ylab() 和其他 ggplot2 函数。

但是我遇到了两个问题:

  1. 如果我不在 roxygen 中 @import,我必须在 list(...) 的每个元素前面加上 ggplot2::。我试过用 lapply 和 paste0 这样做,但它只适用于字符串,当我尝试在 lapply 中调用 xlab() 和 ylab() 时。

  2. 如果我 @import all of ggplot2,我可以在没有 ggplot2:: 的情况下使用 ggplot(),但 Reduce() 会返回 Error in ylab("Mean growth") : could not find function "ylab". 但是,如果我将 ggplot2:: 添加到我的论点,它就可以正常工作。

我这样调用 make_plot :

make_plot(test.summary, dose, statistic, groups = supp,
          error.params = list(width = .5),
          graph.params = list(colour = "black"),
          xlab("Dose (mg)"), ylab("Mean growth"))

除非我用 ggplot2::xlab() 等替换 xlab(),否则这不起作用。

有没有办法避免强制使用 ggplot2:: 或在我的函数前面加上 ggplot2:: 没有用户输入?

标签: rnamespaces

解决方案


推荐阅读