[R] returning a list of functions
Bert Gunter
gunter.berton at gene.com
Wed Jan 27 21:25:42 CET 2010
Lazy evaluation.
Consider:
> funlist <- list()
> for (i in 1:5)funlist[[i]]<- eval(bquote(function(x)x^.(i)))
> str(funlist[[2]])
function (x)
- attr(*, "source")= chr "function(x)x^.(i)"
> funlist[[2]]
function(x)x^.(i)
> ## But...
> body(funlist[[2]])
x^2L
> body(funlist[[3]])
x^3L
>
> funlist[[2]](2)
[1] 4
> funlist[[3]](2)
[1] 8
?bquote
See Bill Venables's "Programmer's Niche" Column on "Mind Your Language" in
the Vol 2/2, June 2002 R News for a fuller explanation. Note that bquote()
is just a kind of "macro-like" version of substitute().
Bert Gunter
Genentech Nonclinical Statistics
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Rajat Mukherjee
Sent: Wednesday, January 27, 2010 7:37 AM
To: r-help at stat.math.ethz.ch
Subject: [R] returning a list of functions
Hi interested readers,
I have a function that creates several functions within a loop and I would
like
them to be returned for further use as follows:
Main.Function(df,...){
# df is a multivariate data
funcList<-list(NULL)
for (i in 1:ncol(df)){
temp<-logspline(df[,i],...) # logspline density estimate
funcList[[i]]<-function(x){expression(temp,x)}
}
return(funcList)
}
I have tried this, unfortunately can't figure out why all the functions
returned are identical.
Any help towards this will be much appreciated. Thanks.
______________________________________________
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.
More information about the R-help
mailing list