[Rd] data() misbehaving inside a function

David James dj at research.bell-labs.com
Thu Oct 16 20:10:29 MEST 2003

Calls of the form data(package = pkg) inside a function 
incorrectly fail ("pkg" is a local variable).  For instance,

   foo <- function(pkg) data(package = pkg)
   Error in .find.package(package, lib.loc, verbose = verbose) :
           none of the packages were found

   ## workaround -- force argument "package" to be an expression
   ## (not a name)

   foo <- function(pkg) data(package = as.character(pkg))
   all.equal(data(package = "base"), foo("base"))
   [1] TRUE

The cause is the following piece of code inside data()

    > print(data)
    if (!missing(package))
               if (is.name(y <- substitute(package)))
                              package <- as.character(y)

namely, when data() is invoked from within a function, e.g.,
data(package = pkg), the argument "package" inside data() is indeed
a name, but not one that should be coerced to character as when one
types data(base) from the R prompt, but rather simply a variable
in the calling function; in the example above, the arg "package"
to data() is effectively computed to be "pkg", which (luckily)
does not correspond to any attached package.

platform i686-pc-linux-gnu
arch     i686
os       linux-gnu
system   i686, linux-gnu
status   Patched
major    1
minor    8.0
year     2003
month    10
day      13
language R

David A. James
Statistics Research, Room 2C-253            Phone:  (908) 582-3082       
Bell Labs, Lucent Technologies              Fax:    (908) 582-3340
Murray Hill, NJ 09794-0636

More information about the R-devel mailing list