Skip to content

complexity of operations in R

1 message · Jan van der Laan

#
See below for the complete mail to which I reply which was not sent to rhelp.
The problem with your addexpandlist2 is that R in principle works with  
pass by value (certainly when you modify the objects you pass in your  
function as you do with prev). Therefore, when you pass your list to  
addexpendlist2 it makes a copy of the entire list.

You can avoid that by using environments that are passed by reference.  
The code below shows an example of this. If you would like to  
implement something like that I would recommend using reference  
classes (see ?ReferenceClasses) . Personally I don't find the 'messy  
code' that messy. You get used to it.

myvector <- function(N = 1000) {
     data <- vector("list", N)
     n    <- 0

     append <- function(d) {
         n <<- n + 1
         if (n > N) {
             N <<- 2*N
             length(data) <<- N
         }
         data[[n]] <<- d
     }

     length <- function() {
         return(n)
     }

     get <- function() {
         return(data[seq_len(n)])
     }

     return(list(append=append, length=length, get=get))
}


h4 <- function(dotot){
     v <- myvector()
     for(i in seq_len(dotot)) {
         v$append(FALSE)
     }
     return(v$get())
}
user  system elapsed
  22.846   0.536  23.407
user  system elapsed
   0.700   0.000   0.702


Jan




Johan Henriksson <mahogny at areta.org> schreef: