I am creating an R package in RStudio. Say I have two functions fnbig()
and fnsmall()
in my package named foo
. fnbig()
is a function that must be accessible to the user using the package. fnsmall()
is an internal function that must not accessible to the user but should be accessible inside of fnbig()
.
# package code
fnsmall <- function()
{
bla bla..
}
#' @export
fnbig <- function()
{
bla bla..
x <- fnsmall()
bla..
}
I have tried exporting fnsmall()
. All works but it litters the NAMESPACE. I tried not exporting fnsmall()
, but then it doesn't work inside fnbig()
when using x <- fnsmall()
or x <- foo::fnsmall()
. Then I tried to use x <- foo:::fnsmall()
, and it works. But I read that using :::
is not recommended.
What is the best way to go about doing this? How do I call an internal function from an exported function?
Every time you start a new R session you'll need to load the packages/libraries that contain functions you want to use, using either library() or require() . If you load a package with the same function name as in another package, you can use packageName::functionName() to call the function directly.
We can find the functions inside a package by using lsf.
What is an internal function? It's a function that lives in your package, but that isn't surfaced to the user. You could also call it unexported function or helper function; as opposed to exported functions and user-facing functions. For instance, in the usethis package there's a. base_and_recommended()
Namespaces are the environment where all the functions of a package live. The parent environments of namespaces are the imports environments, which contain all the functions imported from other packages.
But I read that using :::is not recommended.
I think you mention this based on the following statement in the manual for writing packages by R.
Using
foo:::f
instead offoo::f
allows access to unexported objects. This is generally not recommended, as the semantics of unexported objects may be changed by the package author in routine maintenance.
The reason for this to be not recommended is that unexported functions have no documentation and as such have no guarantee from the side of the package author that they will keep doing what they do now.
However, since you are referring to your own unexported functions, you have full control of what is happening in those functions, so this objection is not as relevant.
Referring to it as foo:::fnsmall
is therefore a good option.
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