[R] package environment versus namespace environment

Benjamin Tyner btyner at gmail.com
Fri Mar 7 16:16:23 CET 2014


Hello,

I realize that a function in <environment: base> (for example, function
"head1" below) is unable to see (without resorting to "::", anyway)
objects in utils (for example, "head" below), since package:base is
after package:utils on the search path.

However, I'm wondering what is the machinery that allows a function in
<environment: namespace:base> (for example, function "head2" below) to
be able to see "head" just fine, without needing to resort to "::".

I'm also wondering more generally, why there is a need (practically
speaking) for a distinction between the environment associated with a
package and the environment associated with the namespace.

   $ export R_PROFILE=/home/btyner/Rprofile.site

   $ cat /home/btyner/Rprofile.site
   sys.source("/home/btyner/head1.R", envir = baseenv())
   sys.source("/home/btyner/head2.R", envir = .BaseNamespaceEnv)

   $ cat /home/btyner/head1.R
   head1 <- function(x) head(x)

   $ cat /home/btyner/head2.R
   head2 <- function(x) head(x)

   $ Rscript -e "head1(letters)"
   Error in head1(letters) : could not find function "head"
   Execution halted

   $ Rscript -e "head2(letters)"
   [1] "a" "b" "c" "d" "e" "f"

   $ Rscript -e "sessionInfo()"
   R version 3.0.1 (2013-05-16)
   Platform: x86_64-pc-linux-gnu (64-bit)

   locale:
    [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C             
    [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8   
    [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8  
    [7] LC_PAPER=C                 LC_NAME=C                
    [9] LC_ADDRESS=C               LC_TELEPHONE=C           
   [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C      

   attached base packages:
   [1] stats     graphics  grDevices utils     datasets  base    

Regards
Ben



More information about the R-help mailing list