Skip to content
Prev 284769 / 398502 Next

calling the function which is stored in a list

On Thu, Feb 9, 2012 at 2:54 AM, arunkumar1111 <akpbond007 at gmail.com> wrote:
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.