[R] Evaluation of functionals

Eric Lecoutre lecoutre at stat.ucl.ac.be
Mon Apr 5 09:43:20 CEST 2004


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] 10

[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 

 > sapply(x<-10, FUN=function(x) x^2)
[1] 100


Eric Lecoutre
UCL /  Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve

tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be

If the statistics are boring, then you've got the wrong numbers. -Edward 

More information about the R-help mailing list