49
votes

tl;dr version of my question

If I want to import packages, do I have to manually write import() directives into my NAMESPACE file? It seems like roxygen2 won't magically do that for me, even if I have them listed as "Imports:" in my description.

Fuller Version

This is a pretty dumb question, but I ask because the answer's not obvious to me.

I use roxygen2 to handle my R package documentation. When I want to be sure a function is exported, I add an @export tag to its roxygen block. Subsequent runs of roxygenize() will write the NAMESPACE directive accordingly.

But, my package currently imports several others:

Depends:
    R (>= 2.13.0),
    ggplot2 (>= 0.8.9)
Imports:
    RColorBrewer,
    plyr,
    gridExtra

It appears that while roxygen2 will rewrite the NAMESPACE directive for exported functions, it won't automatically rewrite NAMESPACE to reflect packages I've designated should be imported in my DESCRIPTION.

1
AFAIK, as long as you tag your function with @imports package or @importsFrom package function, roxygen2 will take care of writing the namespace directives.Ramnath
Currently, the namespace roclet will modify NAMESPACE but not DESCRIPTIONhadley
to avoid the confusion I had, @Ramnath is right, but it should be @importFrom package function, not --@importsFrom.(no s)ldecicco
@RobinL I think you have two options. Say the package you want to import is dplyr. Option 1: use @import dplyr in the roxygen block of your .R file, then refer to dplyr functions in your code like this: select(). Option 2 is to put dplyr in the Imports: field of your DESCRIPTION, then use :: notation in your R files, like this: dplyr::select. If you're using the package a lot in a given file, I suggest you use @import. If you only use it a little, I suggest double colon notation and listing it ONLY in Imports: .briandk
@RobinL > It’s common for packages to be listed in Imports in DESCRIPTION, but not in NAMESPACE. In fact, this is what I recommend: list the package in DESCRIPTION so that it’s installed, then always refer to it explicitly with pkg::fun(). Unless there is a strong reason not to, it’s better to be explicit. It’s a little more work to write, but a lot easier to read when you come back to the code in the future. The converse is not true. Every package mentioned in NAMESPACE must also be present in the Imports or Depends fields. Source: r-pkgs.had.co.nz/namespace.html#importsbriandk

1 Answers

45
votes

Expanding on my comment, if you want to automatically add namespace directives for packages/functions you import, you can do so by adding the @imports package or @importFrom package function line to the roxygen2 documentation header of your function.

However, as @hadley pointed out, it will only modify the NAMESPACE, but not affect the package DESCRIPTION