initialising a vector of objects

Hi all, I would like to create a collection of custom R6 objects, presumably as a vector. I want to set the length of the vector upfront so that I'm not appending to the vector and paying dynamic memory allocation penalties, but I'm wondering if there's any good way to do this. This vector could get to a modest size (hundreds maybe thousands) and I'm looking for advice on how to fill the collection in the most efficient way possible. Thanks much!

Cheers!

You could allocate a list of desired length with vector():

# dummy R6 class
Month <- R6::R6Class("Month", 
  public = list(
    x = NULL, initialize = \(x) self$x = x, 
    print = \() cat("<Month> of", self$x))
)

lst <- vector(mode = "list", length = 12) |> setNames(1:12)
for (idx in seq_along(lst)) lst[[idx]] <- Month$new(month.name[idx]) 
lst[c(1,12)]
#> $`1`
#> <Month> of January
#> $`12`
#> <Month> of December

Though if you already have all arguments for constructors of all your objects, you could just use Map() or *apply() / purrr::map*() family functions and let those handle allocation and iteration:

lst_2 <- 
  setNames(month.name, 1:12) |> 
  lapply(Month$new)
lst_2[c(1,12)] 
#> $`1`
#> <Month> of January
#> $`12`
#> <Month> of December

Thanks much for this! Sorry that I forgot to respond and thank you sooner.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.