Matteo Fasiolo
Matteo Fasiolo

Reputation: 561

How to manage internal utility functions shared by two R packages

I am developing an R package but I would like to break it down into two packages, say A and B, where B depends on A.

In the course of development I have created a number of internal utility functions, say .util1(), .util2(), etc. They are useful to keep my code tidy and avoid repetitions, but I don't want to export them and make them available to other users.

Rather than having one copy of these functions in both A and B, my idea was to put all of them in package A, and then access them from A using B:::.util1(), ... etc. On the other hand that doesn't look very neat, and I will have to document all these "hidden" dependencies somewhere (given that I will not explicitly export them from A). Are there other alternatives? Thanks!

Upvotes: 0

Views: 363

Answers (1)

xb.
xb.

Reputation: 1677

How about this, using the "zoo" package and its internal variable ".packageName" for illustration purpose. You may replace them with the names of your package and internal variable/function when testing.

library(zoo)                              # Load a library
zoo:::.packageName                        # Access an internal variable
.packageName                              # A test - Fail to call without the Namespace
pkg.env <- getNamespace("zoo")            # Store the Namespace
attach(pkg.env)                           # Attach it
.packageName                              # Succeed to call directly !
detach(pkg.env)                           # Detach it afterward

(Edited)

## To export an internal object to the current Namespace (without "attach")
assign(".packageName",get(".packageName",envir=pkg.env))

## Or using a loop if you have a few of internal objects to export
for (obj_name in a_list_of_names) {
  assign(obj_name,get(obj_name,envir=pkg.env))
}

Upvotes: 2

Related Questions