Longtime OOP developer here spinning up on R and R6. I'm used to having namespaces to hold the classes (e.g., Geom::Point, Vital::BloodPressure). I haven't found a way to do that in R. I'm not building a package but I'm not against it if that is the solution.
How can I namespace R6 classes in the R Language?
124 views Asked by Michael Lee Squires At
2
There are 2 answers
0
On
Consider using the box package available on CRAN. You can find the GitHub here or view the author's website documentation here
It allows you to turn basic R scripts into modules - effectively namespacing the code. It sounds like this is what you may want. You will need to use very simple roxygen2 syntax to get it to work.
The usual way to do this is to put your class(es) in a package. Base R infrastructure knows nothing about R6, so you'll definitely want to use
roxygen2to handle the documentation for the classes and methods.The package always defines a namespace, and you can refer to objects exported from it as
pkgname::objectname. While debugging, you can also refer to internal objects that are not exported from the namespace, usingpkgname:::objectname(i.e. three colons). Don't do that in the published version of the package. Neither of those qualifiers is necessary for functions/methods defined within the package. That's all standard R scoping. R6 also has its own rules.Edited to add:
In the comments you said a motivation was this:
Those are likely too closely related to want to put them in separate packages, so in R they likely wouldn't be in separate namespaces. I assume the point of
Lib1andLib2is to isolate local helper functions. In R, one way to do that is to define the helpers within the main functions, e.g.Scoping rules in R mean that the two helpers have read access to all local variables in
DoSomething, and can modify values there using the<<-"super-assignment" operator.Some people don't like this style, and some tools don't support it properly. For example, RStudio can't set breakpoints in the local functions. (This is despite the fact that the base function
utils::setBreakpointcan do so.) The basedebug()function only works on the local functions if you run it withinDoSomethingafter they have been created: the definitions are executable code, not declarations.One more addition:
Another difference between R and some other languages is the fact that
::is an executable operator, it's not just a declaration of where to look for a variable. Once you realize that, you'll realize that the$operator gives another way to fake a namespace. You create an environment, and put your functions into that environment. If you do it properly, they can see each other.And for yet another way to do it, you can use the
local()function to create hidden functions. For example, the code above could have been written like this: