Ozeuss Ozeuss - 4 days ago 6
R Question

Referring to other function inside a local R package

I'm writing a local package that I intend to use for analysis (instead of using a script like I did until now). I have some trouble understanding R's way of sourcing/scoping this way. say I have a R/some_functions.R file, which contains:

#' function a
#' @export
a <- function(a) {
print(a)
}

#' function b, not exporting
b <- function(b) {
print(b)
}

#' function c
cc <- function() {
a("cat") # will run
b("dog") # will not run, can't find function.
}


I understand that function "a" is accessible through the NAMESPACE when I install/load the package, but I still expected function "b" to be available internally. Since I'm the only intended user of the package I can export all , but I want to know the right approach.
just export? sourcing? using devtools::load_all?

EDIT: by dummy code was not good enough. modified it. I think the source of my misunderstanding was that I was expecting code to be attached, which is obviously not the case.

Answer

You're right, when you export a function, it will be available when the package is loaded. When writing a package, you should only export function that are essential to what the package is achieving.

That said, every function you write in your package are available inside the package, exported or not.

To use a function which is not exported outside your package, you can use this synthax: your_package:::b().

See the namespace section on r-pkgs for a more detailed explanation.

Comments