tags:

views:

81

answers:

3

How do you solve the dependencies of packages within your functions? I add require(package) into the function, but I wonder if there's a preferred way of accomplishing this task.

+2  A: 

According to the function's help, require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist

and later on...

The source code for a package that requires one or more other packages should have a call to require, preferably near the beginning of the source, and of course before any code that uses functions, classes or methods from the other package

Brani
A: 

The standard format seems to be

if(!require(the_package))
{
  #Maybe try an alternative or do some cleanup here
  stop("You must install the package 'the_package'.")
}

If your package uses another package widely, then you should load that package when your package is initialised, i.e. in the .First.lib function add it to the Depends field of your package Description file. If the package is only used by one or two of your functions, then this chunk of code goes at the start of those functions.

Richie Cotton
Do you know if there is a function that does likeif(!require(the_package)){ install.packages("the_package"); require(the_package)}
Etiennebr
@Etiennebr: I don't think so, since users can be particular about installing packages themselves, rather than have functions surreptitiously do it for them.
Richie Cotton
+2  A: 

By using the Depends: field of the DESCRIPTION file of your package.

This is yet-another reason why you are better of using packages rather than just making-do with files you are source()-ing.

Edit: There is also Imports: in DESCRIPTION. But the general point is that R has a dependency mechanism and you will be better off if you use it.

Dirk Eddelbuettel