From h.wickham at gmail.com  Fri Sep 12 23:06:33 2014
From: h.wickham at gmail.com (Hadley Wickham)
Date: Fri, 12 Sep 2014 17:06:33 -0400
Subject: [Rd] requireNamespace() questions
In-Reply-To: <541345DD.1090001@gmail.com>
References: <541345DD.1090001@gmail.com>
Message-ID: <CABdHhvF=FhZoP5PLZa4KevAGRPmtLQfp9FLryQfWFZFNzsdwMA@mail.gmail.com>

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/



[Rd] requireNamespace() questions
Hadley Wickham