How do I prevent "r 'library' or 'require' calls not declared" warnings when developing a package?
The most likely candidate is that your functions contain unnecessary calls to require(<pkg>)
or library(<pkg>)
. The error message is a bit misleading -- it's telling you that you've placed require
or library
calls in your code, but haven't actually (properly) declared those calls in your DESCRIPTION
file.
If your intention was to use code from those packages in your own package, then you don't need these library
/ require
calls; rather, you need to properly declare that you're using those packages (and how you're using them) in your DESCRIPTION
file.
Most likely, you want to 'import' the package and make some, or all, of its exported functions / symbols available to your package. You can add such packages to the Imports:
field in your DESCRIPTION
file -- as e.g.
Imports: <pkg>
and similarly, declare that you want to use all exported symbols from that package by writing, in the NAMESPACE
file,
import(<pkg>)
By doing this, all of the functions in <pkg>
's namespace are automatically made available and hence it is not necessary to require
that package anywhere in your code.
Within the context of a package, the main use of require
is for functions that you would like make available only conditionally. For example, suppose you write a function that handles a very specific plotting method which requires foo
, but foo
is otherwise un-needed in your package. So, if you wanted to include code that conditionally depends on package foo
, you can write something of the form:
if (require("foo")) {
#do stuff
}
and then you can include foo
in the DESCRIPTION
under Suggests:
rather than Imports:
. Another example is a package used in producing a vignette but is never required by the users of your package.
In sum: if you are importing a package only to use the functions exported in that package's namespace, you don't need to library
or require
it anywhere in your package code.
EDIT: In newer versions of R, R CMD check
may warn if you use require
, and instead suggest you use requireNamespace
. In that case, you can follow the pattern:
## Use the 'bar' function from package 'foo'
if (requireNamespace("foo", quietly = TRUE)) {
foo::bar()
}
FYI, it's bad form to import all functions of package (when you don't use them) with:
@import package
Better to just
package::thisOne()
When you need it, or
@importFrom package thisOne
If you use a particular function repeatedly