[Rd] requireNamespace() questions

Hadley Wickham h.wickham at gmail.com
Fri Sep 12 23:06:33 CEST 2014


On Fri, Sep 12, 2014 at 3:13 PM, Paul Gilbert <pgilbert902 at gmail.com> wrote:
>
> I am trying to follow directions at
> http://cran.r-project.org/doc/manuals/r-patched/R-exts.html#Suggested-packages
> regarding handling suggested packages with requireNamespace() rather than
> require(), and I have some questions.
>
> 1/ When I do requireNamespace() in a function is the loading of the
> namespace only effective within the function?

Loading the namespace is (effectively) permanent. But the only thing
loading the namespace does is trigger the .onLoad() if present; it
does not affect the search path.

> 2/ At the link above in the manual it says "Note the use of rgl:: as that
> object would not necessarily be visible...".   When the required package is
> loading methods, will the method be found when I reference the generic,
> which is not in the package, or do I need to do something different?

Method should be found correctly.

> 3/ In some packages I have functions that return an object defined in the
> suggested package being required. For example, a function does
> require("zoo") and then returns a zoo object. So, to work with the returned
> object I am really expecting that zoo will be available in the session
> afterwards. Is it recommended that I just check if the package is available
> on the search path the user has set rather than use require() or
> requireNamespace()?.

That may be a reasonable place to require(), in my opinion.

> 4/ I have a function in a package that Depends on DBI and suggests RMySQL,
> RPostgreSQL, RSQLite. The function uses dbDriver() in DBI which uses
> do.call(). If I use requireNamespace() in place of require() I get
>
>> requireNamespace("RMySQL")
> Loading required namespace: RMySQL
>> m <- dbDriver("MySQL")
> Error in do.call(as.character(drvName), list(...)) :
>   could not find function "MySQL"
>
>> require("RMySQL")
> Loading required package: RMySQL
>> m <- dbDriver("MySQL")
>>
>
> Is there a different way to handle this without altering the search path?

I think it's best to do

m <- dbConnect(RMySQL::MySQL, ...)

and avoid do.call() where possible. (I'm pretty sure it is possible,
but it may require changes to the DBI backends), many of which assume
the package to be on the search path.

do.call() probably doesn't do what you think it does:
http://rpubs.com/hadley/do-call2

Hadley

-- 
http://had.co.nz/



More information about the R-devel mailing list