Skip to content

calling the function which is stored in a list

4 messages · arunkumar1111, Uwe Ligges, Gabor Grothendieck

#
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)

Thanks

-----
Thanks in Advance
        Arun
--
View this message in context: http://r.789695.n4.nabble.com/calling-the-function-which-is-stored-in-a-list-tp4372131p4372131.html
Sent from the R help mailing list archive at Nabble.com.
#
On 09.02.2012 08:54, arunkumar1111 wrote:
Yes, if you correct the typo and use list indexing with double brackets:

function3[[1]](x)

Uwe Ligges
#
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.