[R] Create function from string

Jon Olav Skoien jon.skoien at jrc.ec.europa.eu
Tue Apr 16 09:50:24 CEST 2013


Dear list,

I am trying to create a function from a string, and have so far solved 
it with eval(parse()). This works well also when using the newly created 
function as an argument to another function. The trouble starts when I 
want to use it with parLapply. Below is a much simplified example:

##############
fstring = "x+2"
FUN = function(x)  eval(parse(text = fstring))
FUN(3)

FUN2 = function(y, func)   y + func(y)
FUN2(3,FUN)

# I can also pass FUN as an argument to FUN2 when using foreach and 
parallel:

library(parallel)
library(foreach)
cl = makeCluster(2, outfile = "")

ylist = list(1:3,4:6)
result = foreach(i = 1:2) %dopar% {
   FUN2(ylist[[i]], FUN)
}

# But now when I wanted to change to parLapply (actually parLapplyLB) 
fstring is not found anymore:
parLapply(cl, as.list(1:4), FUN2, func = FUN)
##############

I assume there is a problem with environments, the question is how to 
solve this. The cleanest would be to substitute fstring with its content 
in FUN, but I did not figure out how. Substitute or bquote do not seem 
to do the trick, although I might not have tried them in the right way. 
Any suggestions how to solve this, either how to substitute correctly, 
or to completely avoid the eval(parse())?

Thanks,
Jon



-- 
Jon Olav Skøien
Joint Research Centre - European Commission
Institute for Environment and Sustainability (IES)
Land Resource Management Unit

Via Fermi 2749, TP 440,  I-21027 Ispra (VA), ITALY

jon.skoien at jrc.ec.europa.eu

Disclaimer: Views expressed in this email are those of the individual and do not necessarily represent official views of the European Commission.



More information about the R-help mailing list