[Rd] data() misbehaving inside a function

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Oct 16 21:06:44 MEST 2003


Yes, but this is not to do with being inside a function:

pkg <- "base"
data(package=pkg)

ilustrates it, and library etc behave in the same way (except
library can make use of character.only = TRUE).

You can use substitute, too, as in

foo <- function(pkg) eval(substitute(data(package = pkg), list(pkg=pkg)))


On Thu, 16 Oct 2003, David James wrote:

> 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)
>    foo("base")
>    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.
> 
> version
>        _
> 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
> 
> 

-- 
Brian D. Ripley,                  ripley at 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



More information about the R-devel mailing list