On Thu, 26 Aug 2010, Jorge Ivan Velez wrote:

Hi pdb,

Take a look at
http://r.789695.n4.nabble.com/test-if-a-package-is-installed-td1750671.html#a1750674

You are citing yourself with a poor solution (calling installed.packages()) -- so please don't.

The help page for installed.packages in R-devel says

Note:

     This can be slow when thousands of packages are installed, so do
     not use this to find out if a named package is installed (use
     ‘system.file’ or ‘.find.package’) nor to find details of a small
     number of packages (use ‘packageDescription’).  It needs to read
     several files per installed package, which will be slow on Windows
     and on some network-mounted file systems.

However, the real question (not the one in the subject line) seems to be 'is this package usable'? The basis for the answer there is require() as others have said, but they have not said that require() can give an error in current R. So you need something like

f_checkpackage <- function(pkg, ...)
   tryCatch(require(pkg, character.only=TRUE, ...),
            error = function(e) FALSE)

For those unaware of the possible differences between 'installed' and 'usable', e.g.

- a dependency of 'pkg' may not be available,

- on Mac OS X packages can be installed for only some of the
  architectures,

- packages may be installed but without the correct external software
  (see the parallel thread on 'rjags').

As from R 2.12.0 require() will contain a tryCatch() test and so always return TRUE/FALSE.



HTH,
Jorge



On Thu, Aug 26, 2010 at 9:07 PM, pdb <> wrote:


Hi,

I am writing a function that requires a specific package to be installed.

Is there a way of checking if the package is installed and returning a TRUE
/ FALSE result so my function can return an appropriate error message and
exit the function gracefully rather than just bombing out?

I'm thinking along the following lines (but want code that works),

f_checkpackage <- function()
{

if (library(madeupname) == TRUE) {
   cat("package loaded OK\n")
}
else
{
    cat("ERROR: package not loaded")
}

}

f_checkpackage()

--
Brian D. Ripley,                  rip...@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to