m0n*_*awk 5 r r-s3 roxygen2 r-package
我坚持定义S3方法autoplot.
我有以下(完整代码在这里):
#' Autoplot for bigobenchmark object
#'
#' @importFrom ggplot2 autoplot
#'
#' @param object
#'
#' @return A ggplot2 plot
#' @export
#'
#' @examples
#' # Create plot for benchmarks
#' library(ggplot2)
#' bench <- bigobenchmark(1:n, for(i in 1:n) for(i in 1:n) 1:n, args=seq(from=1, to=100, length.out = 50))
#' autoplot(bench)
autoplot.bigobenchmark <- function(object) {
plt <- ggplot2::ggplot(data = object$benchmarks, ggplot2::aes(x=arg, y=mean, colour=expr))
plt <- plt + ggplot2::geom_line()
plt <- plt + ggplot2::geom_pointrange(aes(ymin=min, ymax=max))
plt
}
Run Code Online (Sandbox Code Playgroud)
据我所知,我应该可以运行,但它失败了:
> autoplot(test)
Error in autoplot(test) : could not find function "autoplot"
Run Code Online (Sandbox Code Playgroud)
为什么没有找到这个功能?我有一个正确的@importFrom ggplot2 autoplot和Roxygen生产正确NAMESPACE.
有一个ggplot2在Imports中DESCRIPTION.
我不知道为什么它不起作用,为什么我需要library(ggplot2)使用它.
导入包时,它"通过命名空间加载(而不是附加)"(引自sessionInfo()).
当您想要使用导入包中的函数时,通常使用结构调用它ggplot2::ggplot(),就像您所做的那样.
因此,使用autoplot你仍然需要使用ggplot2::autoplot().
如果不这样做,您的包装不知道该autoplot功能ggplot2.
有一些解决方案:
Depends: ggplot2(请参阅下面的链接以了解有关Importsvs 的讨论Depends,以及1.1.3节或编写R扩展名 ]plot方法,然后调用各种ggplot2::ggplot()函数autoplot.bigobenchmark,但要求用户ggplot2在使用之前加载(实际上这个例子在动物园包中.另见?zoo::autoplotautoplot函数,但如果用户稍后加载ggplot2,则可能会导致冲突这是解决方案2的一个例子
#' plot for bigobenchmark object
#'
#' @importFrom ggplot2 autoplot
#'
#' @param object
#'
#' @return A ggplot2 plot
#' @export
#'
#' @examples
#' # Create plot for benchmarks
#' library(ggplot2)
#' bench <- bigobenchmark(1:n, for(i in 1:n) for(i in 1:n) 1:n, args=seq(from=1, to=100, length.out = 50))
#' plot(bench)
#'
#' @author Andrew Prokhorenkov
plot.bigobenchmark <- function(object) {
plt <- ggplot2::ggplot(data = object$benchmarks, ggplot2::aes(x=arg, y=mean, colour=expr))
plt <- plt + ggplot2::geom_line()
plt <- plt + ggplot2::geom_pointrange(ggplot2::aes(ymin=min, ymax=max))
plt
}
Run Code Online (Sandbox Code Playgroud)
这是解决方案4的一个例子
#' Autoplot for bigobenchmark object
#'
#' @importFrom ggplot2 autoplot
#'
#' @param object
#'
#' @return A ggplot2 plot
#' @export
#'
#' @examples
#' # Create plot for benchmarks
#' library(ggplot2)
#' bench <- bigobenchmark(1:n, for(i in 1:n) for(i in 1:n) 1:n, args=seq(from=1, to=100, length.out = 50))
#' autoplot(bench)
#'
#' @author Andrew Prokhorenkov
autoplot <- function(object) UseMethod("autoplot")
#' @export
autoplot.bigobenchmark <- function(object) {
plt <- ggplot2::ggplot(data = object$benchmarks, ggplot2::aes(x=arg, y=mean, colour=expr))
plt <- plt + ggplot2::geom_line()
plt <- plt + ggplot2::geom_pointrange(ggplot2::aes(ymin=min, ymax=max))
plt
}
Run Code Online (Sandbox Code Playgroud)
在这个SO答案中,Josh O'Brian和majom(引用Hadley)给出了对Importsvs 的更好解释Depends