[R] How to use current value of variable in function definition?

Allan Engelhardt allane at cybaea.com
Thu Jul 2 22:22:08 CEST 2009


On 02/07/09 21:02, Mark Wardle wrote:
> Hi.
>
> I've stared at your code for a number of minutes and can't understand
> what you're trying to achieve here. It looks as if you're fighting
> scope - it may be worth refactoring your approach to simplify matters.
> Otherwise, it sounds like a recipe for obfuscation! What are you
> trying to do really?
>
> b/w
>
> Mark
>
> 2009/7/2 Allan Engelhardt<allane at cybaea.com>:
>    
>> Must be the heat or something but I can't get my brain into gear and figure
>> out how to get something like
>>
>> if (1) { c<- 1; foo<- function () print(c); }
>>      

Imagine "c <- 1" is a long complex operation, say to get a list of 
current active EC2 hosts through querying some web services and some 
complex system("ssh...") calls that I do not want to repeat ever again, 
and the result is a list of hosts (and it is not really called "c" - 
that would be bad).  My function foo is a parallel version of lapply and 
the code goes something like

if ( usingAmazonWebServices() ) {
     cluster <- myServers(); # Takes minutes
     p.lapply <- function (...) aws.lapply(..., hosts = cluster)
} else if ( require("multicore", ...) ) {
     p.lapply <- function (...) mc.lapply(..., mc.preschedule = FALSE)
} else {
     p.lapply <- lapply
}
## ...
## Much later:
result <- p.lapply(problems, analysis)

This is somewhere far away from the main action of the code and my fear 
is that somewhere someone (most likely me next week) will accidentally 
use the "custer" variable for something else, causing p.lapply to 
mysteriously fail.  I probably should package it all up and use 
namespaces or some such, but I am just trying not to get hurt right now.

Allan




More information about the R-help mailing list