[R] Create function from string
peter dalgaard
pdalgd at gmail.com
Tue Apr 16 10:21:12 CEST 2013
Is this what you are looking for?
> FUN = eval(bquote(function(x) .(parse(text = fstring)[[1]])))
> FUN
function (x)
x + 2
> FUN(3)
[1] 5
On Apr 16, 2013, at 09:50 , Jon Olav Skoien wrote:
> 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.
>
> ______________________________________________
> 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.
--
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list