egnha egnha - 2 months ago 10
R Question

Export a list of functions with roxygen2

Problem — I want to export a list of functions as part of an R package, ideally using roxygen2.

To be more precise, I want to export the functions in the list, rather than the list itself. For example, consider a list of functions that are generated as closures, like so:

addval <- 1:100
fns <- lapply(addval, function(y) {force(y); function(x) x + y})
names(fns) <- paste0("add_", addval)

Then the problem is to bind the functions (using the same names in
, for instance) to the package environment, and then include them among the exported functions of the package.

Binding the functions to the package environment can be done easily enough; one way would be

for (nm in names(fns)) assign(nm, fns[[nm]])

But is it then possible to use roxygen2 tags to export the functions
, etc.?

More to the point: I would like roxygen2 to continue managing the
file for me, and would prefer not to have to write
calls, directly. The only way I can see doing that is by writing code to generate boilerplate like

#' @export add_1

#' @export add_2

# ...

or better

#' @export
add_1 <- fns[["add_1"]]

#' @export
add_2 <- fns[["add_2"]]

# ...

(and forgo the above for-loop).

Does roxygen2 already have a facility equivalent to such boilerplate generation, or would I have to provide this facility myself?

I have in mind such a facility being expressed more succinctly as

#' @exportObjects names(fns)

where the tag
would interpret its "argument" as a character vector of names of objects to export.


roxygen2 6.0.1+ solves this problem with a new
tag, which allows you to insert literal entries in the NAMESPACE file:

ns_export <- function(nms)
sprintf("export(%s)", paste(nms, collapse = ","))

#' @evalNamespace ns_export(names(fns))

Answer Source

You can use the @rawNamespace tag in recent roxygen2, this allows using arbitrary syntax valid in a NAMESPACE file, including exportPattern():

#' @rawNamespace exportPattern("^add_.*$")