Skip to content

"local({})" documentation?

3 messages · Doug Elias, Duncan Murdoch, Martin Morgan

#
On 08/04/2011 2:11 PM, Doug Elias wrote:
Try ?local.  As with other help pages, you may find it too terse, but 
that's different than "a complete blank".

Duncan Murdoch
#
On 04/08/2011 11:11 AM, Doug Elias wrote:
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