[R] Defining/Checking constants in packages
Luke Tierney
luke at stat.uiowa.edu
Thu Nov 21 16:17:28 CET 2002
On Thu, 21 Nov 2002 ripley at stats.ox.ac.uk wrote:
> On Wed, 20 Nov 2002, Deepayan Sarkar wrote:
>
> >
> > Although namespaces are not fully implemented yet, the base namespace does
> > work in R 1.6.x. e.g.,
> >
> > > pi <- 90
> > > pi
> > [1] 90
> > > base::pi
> > [1] 3.141593
> >
> > (Of course, there might be other ways as well.)
>
> > get("pi", envir=.GlobalEnv)
> [1] 3.141593
>
> is equivalent and works in all versions of R. Just use it, rather than
> assigning the value.
Brian probably meant to use envir=NULL or pos="package:base". Using
envir=.GlobalEnv is equivalent to just
> pi
[1] 3.141593
which is subject to masking by loaded packages and assignments to
.GlobalEnv. base::pi is equivalent to
> get("pi", pos="package:base")
[1] 3.141593
or
> get("pi", envir=NULL)
[1] 3.141593
To expand on Brian's point, even if you did assign a value to pi in
your package that would only prevent masking by packages loaded prior
to yours. Your functions are defined in the global environment, so
their globals are looked up in the global environment, the search
list, and then base. If a package that does pi<-3 is loaded after
yours or if the user makes such an assignment at top level, then the
value your package gets for pi is 3. Using base::pi in the current R
or get("pi", pos="package:base") is safer.
Within a month the development version of R should have a name space
mechanism that allows a package to explicitly specify which other
packages it uses (imports); functions in a package using this
mechanism will be defined in an environment that searches the package
itself, explicit imports (if any), and then base before .GlobalEnv and
attached packages. This insures that attaching packages and assigning
into .GlobalEnv will not be able to mask definitions used in your
code.
As of 1.6 the base package is already defined in a name space, so any
functions in base that use pi will see the definition in base;
redefining pi in a loaded package or at top level cannot affect these
functions.
luke
--
Luke Tierney
University of Iowa Phone: 319-335-3386
Department of Statistics and Fax: 319-335-3017
Actuarial Science
241 Schaeffer Hall email: luke at stat.uiowa.edu
Iowa City, IA 52242 WWW: http://www.stat.uiowa.edu
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list