[R] Problem accessing sub-methods of functions stored in a vector

Matt Asher status at quo.org
Fri Feb 26 16:33:37 CET 2010


Hi folks,

I am having trouble accessing sub-functions when the main function is 
stored in an array. For example, the following test code works fine:

fcns = c(abs, sqrt)
fcns[[1]](-2)
fcns[[2]](2)

However, when I try to access sub-functions declared within list() in a 
function, this only works directly. When I try to access these within an 
array only the first declared sub-function is run. For example I have 
the function:

agent <- function(id) {
 
 # MANY VARIABLES DECLARED
 
  list( 
     set_id = function(newid) {
         id <<- newid
    },
   
    get_id = function(newid) {
        return(id)
    },

    # LOTS MORE SUB FUNCTIONS
    )
}

If I create a variable to hold this function, I can then access all the 
subfunctions without problem Example:

myAgent = agent(1)
myAgent$get_id() # Works fine

However, once this function is stored in a vector, I can no longer 
access the subfunctions.

agents = c(agent(1), agent(2))

agents[[1]] # This shows the set_id function only, unnamed

agents[[1]]$get_id() # Leads to error below:

Error in agents[[1]]$get_id : object of type 'closure' is not subsettable

How can I access these sub methods within the vector?

I am using R version 2.8.1

TIA for the help!



More information about the R-help mailing list