I have defined three different S4 classes in their own scripts in my R package. One of those classes uses the other two classes.
I see that devtools::load_all()
loads the scripts in alphabetical order, so that if a script depends on another that is later in alphabetical order, there may be problems. Observe:
Example script a.r
:
setClass("a", slots = c(name = "character"))
Example script b.r
setClass("b", slots = c(name = "character", a = "a", c = "c"))
Example script c.r
:
setClass("c", slots = c(name = "character"))
When I run devtools::load_all()
, the following warning appears:
Warning messages:
1: undefined slot classes in definition of "b": c(class "c")
I do not want to rename my scripts simply to put them in alphabetical order based on when I want them to be loaded.
I do not want to define those classes in a single script, because I want to keep the code more modular.
How do I ensure that the script defining the dependent class has access to the other classes:
source()
since this would import other functions, objects, variables, from that script that are not needed.In python
, this is relatively trivial. One uses a syntax like:
from <relative path to .py file that defines those objects> import <desired objects>
In R
, I am spinning in circles trying to accomplish something similar.
I found a suitable solution by digging into the Collate
field in the DESCRIPTION
file.
When I append this to the DESCRIPTION
file, then the warning goes away when I run devtools::load_all()
because files will be loaded in the order I specified rather than alphabetical order:
Collate:
a.r
c.r
b.r
This does not answer the more general question about how to replicate the behavior of python
by only importing specific objects defined in another script... The load_all()
functionality still seems to load everything in the scripts, and the Collate
section simply specifies the order... But I'll still count this as a win.