Skip to content
Prev 11081 / 12125 Next

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

On 2024-12-04 1:25 p.m., Adelchi Azzalini wrote:
The usual way to do this is to list the package in Suggests, and then 
wrap any use of it in `if (requireNamespace("pkg")) { ... }` blocks. 
This doesn't quite import the functions, you would need to use the 
`pkg::fn` syntax to access the functions.

If you really want to simulate importing so that you don't need the 
`pkg::` prefix, you could do it this way:  In the `.onLoad` function of 
your package, you would have code like

   if (requireNamespace("pkg")) {
     foo <- pkg::foo
     bar <- pkg::bar
   } else {
     foo <- stub
     bar <- stub
   }

where `stub` is a function that says "you need `pkg` to use this function".

Duncan Murdoch