[R] calling the function which is stored in a list
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Feb 9 17:46:35 CET 2012
On Thu, Feb 9, 2012 at 2:54 AM, arunkumar1111 <akpbond007 at gmail.com> wrote:
> Hi
>
> I'm storing two functions in a list
>
> # creating two function
> function1 <- function(n) {
> return(sum(n))
> }
>
> function2 <- function(n) {
> return(mean(n))
> }
>
> #storing the function
> function3 =c(function1,function2)
>
> is it possible to call the stored function and used it ?
>
> x=c(10,29)
> funtion3[1](x)
>
In addition to [[ as in the other response also try this:
L <- list(function1 = sum, function2 = mean)
L$function1(1:3)
Note that the proto package is somewhat similar but stores functions
in environments rather than lists and also supports a type of object
oriented programming:
library(proto)
p <- proto(function1 = function(., n) sum(n),
function2 = function(., n) mean(n),
function3 = function(.) mean(.$x),
x = 1:10
)
p$function1(1:3)
p$function3() # mean of 1:10
p$x <- 1:5
p$function3() # mean of 1:5
# define child p2 with its own x overriding p's x
p2 <- p$proto(x = 10:15)
# p2 has its own x so this is mean of 10:15
# p2 inherits its methods from p so its has a
# function3 too
p2$function3()
p$function3() # p unchanged. Still mean of 1:5.
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list