Skip to content

returning a list of functions

2 messages · Rajat Mukherjee, Bert Gunter

#
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.
#
Lazy evaluation. 

Consider:
function (x)  
 - attr(*, "source")= chr "function(x)x^.(i)"
function(x)x^.(i)
x^2L
x^3L
[1] 4
[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.