Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Calling internal function from an exported function inside package

Tags:

r

r-package

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?

like image 368
rmf Avatar asked Jan 04 '16 10:01

rmf


People also ask

How do you call a function from a package in R?

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.

How do I view a function within an R package?

We can find the functions inside a package by using lsf.

What is an internal function in R?

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()

What is a namespace in R?

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.


1 Answers

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 of foo::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.

like image 123
JAD Avatar answered Nov 15 '22 23:11

JAD