Reputation: 1192
I am building a simple R package with many auxiliary functions. One of the main function uses a lot of the auxiliary ones as such:
....
#'@ description
#'@ param
#'@ export
...
mainfunction1 <- function(param1,...,auxiliaryfunction){
# Do some stuff
b <- auxiliaryfunction(param2) + c
return(b)
}
...
#'@ description
#'@ param
auxiliaryfunction1 <- function(param5,param6,...){# do stuff}
The main function should be used by the final user as such:
result1 <- mainfunction1(param1, param2, auxiliaryfunction1)
The problem is that when the package is built, it never finds the auxiliary functions unless they are exported, however I'd like them not be available to the final user or at least avoid the problem of the user overriding them by mistake by referring to the package namespace.
How can I do this? Should I export the auxiliary functions too?
Upvotes: 1
Views: 296
Reputation: 44525
You are trying to solve a non-problem.
If you want a user to use a function, export it.
If you don't want a user to use a function, do not export it.
That said...
There is a possibility that you are getting caught up on how functions are passed as arguments to other functions. Functions are first class objects in R, so they can be passed around very easily. Consider the following example:
m <- function(x, y) x + y
n <- function(x, y) x - y
k1 <- function(x, y, FUN) FUN(x, y)
k1(10, 5, FUN = m)
# [1] 15
k1(10, 5, FUN = n)
# [1] 5
k2 <- function(x, y, FUN = m) FUN(x, y)
k2(10, 5) # uses `m()` by default
# [1] 15
k2(10, 5, FUN = m)
# [1] 15
k2(10, 5, FUN = n)
# [1] 5
If you really don't want to users to access the functions directly but want to give them choice over which to use, then define the auxiliary functions in the body of the main function and use, for example, a switch()
to choose between them:
fun <- function(x, method = c("A", "B")) {
m <- match.arg(method)
a <- function(x) x^2
b <- function(x) sqrt(x)
switch(m, A = a(x), B = b(x))
}
fun(2)
# [1] 4
fun(2, "A")
# [1] 4
fun(2, "B")
# [1] 1.414214
Upvotes: 2