I'm building a very basic R package for my own use.
Some of the files need a function in another file.
So the R files try to source an R file. This fails during build. Neither
source("./util.R")
nor
source ("util.R")
work. R can't find the file.
All of the files are in the R directory of the package.
How do I call the file to make sure that it is found?
Thanks,
I think sourcing (source
) is not required within a package since there must be kinda "lazy evaluation" (just parsing) of the objects you create that postpones the evaluation until you really call the functions of a package (which is a library = collection of functions that wait to be called from outside).
Hadley Wickham explains the background in his book R packages in the section "Top-level code".
To test this behaviour I have created a package using RStudio and added two files that call functions of the other file (like a circular reference):
File "f1.R":
f1 <- function() {
print("f1")
f2()
}
f4 <- function(a) {
print(paste("f4:", a))
}
File "f2.R":
# f2.R
f2 <- function() {
print("f2")
}
f3 <- function(a) {
print(paste("f3:", a))
f4(a)
}
RStudio creates a (source) package from this without problems.
I can also load the package, call the functions and the result is as expected:
> library(testpackage)
> testpackage:::f1() # ::: allows calling a hidden function that was not exported. You could also create a NAMESPACE file instead
[1] "f1"
[1] "f2"
> testpackage:::f3("hello")
[1] "f3: hello"
[1] "f4: hello"
>
Summary: No source
required in packages (until you want to test your code files without building a package before!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With