[R] a question about scoping functions

Roger D. Peng rpeng at jhsph.edu
Wed Mar 31 01:48:48 CEST 2004


I wrote a function a while back that does something like "attaching" R 
source files.  The code in the R file is attached in the second position 
on the search list.  I actually don't use it much but you may find it 
useful.


sattach <- function(filename) {
     if(!is.character(filename))
         stop(sQuote("filename"), " must be character string")
     e <- new.env()
     eval(parse(filename), envir = e)
     func.list <- lapply(ls(e), get, envir = e)
     names(func.list) <- ls(e)
     outobj <- make.names(basename(filename))
     assign(outobj, func.list)

     cmd <- paste("attach(", outobj, ")", sep = "")
     eval(parse(text = cmd))
}

-roger

Rajarshi Guha wrote:

> Hi,
>  I've written some helper functions which are used by another function
> (called func()). When func() is sourced I dont want the helper function
> to be seen in the global namespace (as shown by ls()).
> 
> Currently what I have done is:
> 
> func <- function() {
>   helper1 <- function() {
>     ...
>   }
>   helper2 <- function() {
>     ...
>   }
>   # some code
> }
> 
> Is there anyway to take the functions helper1 and helper2 outside func
> (but in the same file) yet keep them from showing up in the global
> namespace when the source file for func() is loaded?
> 
> A related question is: say I move helper1 and helper2 to a file called
> helper.R
> 
> When I want to use the helper functions inside func() I can do
> source('helper.R') - but that would place them in the global namespace.
> Is it possible to source some file within a func() such that the sourced
> functions will be local to func()?
> 
> Thanks,
> -------------------------------------------------------------------
> Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
> GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
> -------------------------------------------------------------------
> Did you hear that two rabbits escaped from the zoo and so far they have
> only recaptured 116 of them?
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list