Search code examples
rloopsfor-loopoopr6

Efficient object creation with R6


I want to create a group of R6 objects from the following example constructor:

myClass <- R6Class("myClass",
                   public = list(
                     height = NA,
                     initialize = function() {
                       self$height <- rnorm(1, 176, 7)
                     })
)

And place them in a new environment:

myEnv <- new.env()

If the group has 10 members, I can do this with a loop:

 for(i in 1:10){  
  assign(paste0("group_member_", i), 
         myClass$new(),
         envir = myEnv)
}

You can imagine this is scaled up, with many more group members, each with many more characteristics.

I'm fairly sure this is either a bad way to do this or a slow way to do this, or both! Therefore, I'm looking for improvements related to both aspects.


Solution

  • You could create them in one go in a list using lapply, then change the list to an environment:

    myenv <- list2env(setNames(lapply(1:10, function(x) myClass$new()), 
                               paste0("group_member", 1:10)))
    
    ls(myenv)
    #> [1] "group_member1"  "group_member10" "group_member2"  "group_member3"  
    #> [5] "group_member4"  "group_member5"  "group_member6"  "group_member7"  
    #> [9] "group_member8"  "group_member9"