[R] "local({})" documentation?

Martin Morgan mtmorgan at fhcrc.org
Fri Apr 8 21:40:46 CEST 2011


On 04/08/2011 11:11 AM, Doug Elias wrote:
> Greetings, all ...
>
> I'm trying to find documentation on the use of the "local()" function, and
> am drawing a complete blank; would someone please send me a pointer to where
> I can learn what it is intended for, and how to correctly use it?

Hi Doug --

?local

It can be useful as a function-ette giving local scope w/out cluttering 
the name space or creating variables that persist after they are needed, 
e.g.,

bar <- local({
     txt = readLines(<some/big/file>)
     ## do some things to reduce big txt, e.g., sample lines
     txt[sample(length(txt), 100)]
})

'bar' is now 100 lines from <some/big/file>; txt no longer exists.

It can also provide a closure, as in the 'snow' package top-level source

getMPIcluster <- NULL
setMPIcluster <- NULL
local({
     cl <- NULL
     getMPIcluster <<- function() cl
     setMPIcluster <<- function(new) cl <<- new
})

now both getMPIcluster and setMPIcluster have access to the same 
variable 'cl'; 'cl' continues to exist after the end of local() because 
there are still references to it (through the environments associated 
with get/set MPIcluster). This is an interesting piece of code for 
understanding R's scoping, environments, and garbage collection.

Martin

>
> Many thanks!
>
> Doug
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109

Location: M1-B861
Telephone: 206 667-2793



More information about the R-help mailing list