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
fns
, 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
add_1
,
add_2
, etc.?


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

#' @export add_1
NULL

#' @export add_2
NULL

# ...


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)
NULL


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

Update



roxygen2 6.0.1+ solves this problem with a new
@evalNamespace
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_.*$")