[R] Evaluation of functionals
Eric Lecoutre
lecoutre at stat.ucl.ac.be
Mon Apr 5 09:43:20 CEST 2004
Hi,
Once again, I think apply family is your friend. Dont forget functions are
objects as any others:
At 09:36 5/04/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.
> lapply(funlist, FUN=function(f) f(10))
[[1]]
[1] 10
[[2]]
[1] 100
Or, better, pass the value as extra-parameter:
> sapply(funlist, FUN=function(f,x) f(x), x=10)
[1] 10 100
>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?
Here again, you can embedd the definition of your function in the [sl]apply
code:
> sapply(x<-10, FUN=function(x) x^2)
[1] 100
Eric
Eric Lecoutre
UCL / Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve
Belgium
tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be
http://www.stat.ucl.ac.be/ISpersonnel/lecoutre
If the statistics are boring, then you've got the wrong numbers. -Edward
Tufte
More information about the R-help
mailing list