ggpubr can't find 'mean_se' unless ggpubr is attached via library()

Viewed 62

Summary of problem: When I try to add summary stats to a ggpubr plot via the "add" parameter, ggpubr can't find the summary stat functions (example code below). For instance, if I am trying to add error bars with add="mean_se" I get an error message and no error bars.

Unsatisfactory solution: Attaching ggpubr by calling library(ggpubr) would fix this problem. See this answer.

Why the above solution is unsatisfactory: I am developing a package, and so would like to avoid attaching other packages via calls to library() - my understanding is that this is best practice, to avoid polluting the namespace with things the user might not have anticipated would get loaded.

MY QUESTION: Is there some way to get ggpubr to find mean_se without attaching the package?

Example code (in an .R file in my package):

make.plot = function(){
  utils::data("iris")
  ggpubr::ggbarplot(
    data = iris,
    x = "Species",
    y = "Sepal.Length",
    add = "mean_se")
}

Example output:

> devtools::load_all(".")
# i Loading MyPackage
> make.plot()
# Warning message:
# Computation failed in `stat_summary()`:
# object 'mean_se_' of mode 'function' was not found 

One thing that should work, but doesn't, is passing "ggpubr::mean_se_" as the add argument. This avoids the error message, but produces an incorrect plot. The plot should look like this:

Desired plot

But passing "ggpubr::mean_se_" instead produces: enter image description here

Additional weirdness: If I ever add a call to load ggpubr, build MyPackage with devtools::load_all("."), and run it, then the above code never fails until I quit and reload RStudio, even if I delete the call library(ggpubr) from my package and build it again.

2 Answers

Since you're creating a package you can ensure that mean_se_ is in the search path by importing it in your function.

If you use roxygen you can add the tag @importFrom ggpubr mean_se_:

#' @importFrom ggpubr mean_se_
make.plot = function(){
  utils::data("iris")
  ggpubr::ggbarplot(
    data = iris,
    x = "Species",
    y = "Sepal.Length",
    add = "mean_se")
}

Then you run devtools::document() and run your function, and your output should look like this:

a plot

If you look at the way the add parameter is handled inside ggpubr, it is actually matched as a string to one of the summary functions. It seems that the summary functions need to be on the search path when ggbarplot is called.

The easiest way round this is to copy the function over to your own package namespace:

mean_se_ <- ggpubr::mean_se_

make.plot = function(){
  utils::data("iris")
  ggpubr::ggbarplot(
    data = iris,
    x = "Species",
    y = "Sepal.Length",
    add = "mean_se_")
}

make.plot()

Created on 2022-05-04 by the reprex package (v2.0.1)

Related