Skip to content
Prev 11084 / 12125 Next

[R-pkg-devel] conditional import of a package?

On 2024-12-05 3:06 a.m., Adelchi Azzalini wrote:
You shouldn't use `require(nloptr, quietly=TRUE)`.  That puts it on the 
search list, and packages should generally not modify the search list.

Just before this in your code, you know that nloptr is loaded.  You 
don't know if it's on the search list or not, and that shouldn't matter.
The code above relies on having nloptr on the search list, and you don't 
know that, so you'll need a different way to set nloptr.method.  Another 
problem is that at this point you don't know if nloptr is loaded or not, 
because the requireNamespace() call above might have returned FALSE.

What I would do is to set nloptr.method in the code block above, i.e. 
change the first block to

     opt.methods <- c("Nelder-Mead", "BFGS", "nlminb")
     if(requireNamespace("nloptr", quietly = TRUE)) {
       nloptr.methods <- c("newuoa", "bobyqa", "cobyla")
       if(opt.method %in%  nloptr.methods)
         nloptr.method <- get(opt.method,
                              envir = loadNamespace("nloptr"))
     } else
       nloptr.method <- function(...) stop("this optimization needs the 
nloptr package.")


The second block could then be simplified to

      if(opt.method %in% nloptr.methods)
         opt <- nloptr.method(<args>)
That should be fine.
You shouldn't need to do that.

Duncan Murdoch