From: Prof Brian Ripley (ripley@stats.ox.ac.uk)
Date: Mon 05 Apr 2004 - 17:49:55 EST
Message-id: <Pine.LNX.4.44.0404050845320.27382-100000@gannet.stats>
On Mon, 5 Apr 2004, Søren Højsgaard wrote:
> Suppose I have
> f1 <- function(x) x
> f2 <- function(x) x^2
> funlist <- list(f1,f2)
> Then I would like to evaluate funlist such that when x is 10 I should get a list with 10 and 100.
>
> A naive way of doint this is
> myf <- funlist[[1]]
> do.call(paste(quote(myf)), list(x=10))
> myf <- funlist[[2]]
> do.call(paste(quote(myf)), list(x=10))
> - but there has to be much more elegant ways of doing this. I just can't
> figure out how..
lapply(funlist, function(f, x)f(x), x=10)
> Put more generally, is there a way of making R "understand"
> automatically that funlist above is really a function of x?
It isn't. It is a list of functions of , so use lapply.
> A related question is that of anonymous functions: how to evaluate
> function(x)x^2 on x<-10 without assigning the function to a name?
> (function(x)x^2)(10)
[1] 100
-- Brian D. Ripley, ripley@stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595______________________________________________ R-help@stat.math.ethz.ch mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
This archive was generated by hypermail 2.1.3 : Mon 03 May 2004 - 18:41:17 EST