Predefined in r

In Matlab, he is drilled in you - prealocate, preallocate, prealocate. If you do not, gremlins will eat processor cycles, and you will be a bad person. Is it really that important to redistribute in r, as it does in Matlab?

+4
source share
2 answers

Since in R we try to avoid explicit loops, this is not so important. Many features do this under the hood for us. Of course, if you insist on using loops for, you should pre-allocate so as not to enlarge the object in the loop (which is one of the slowest operations you can do). Relevant reading material: The R Inferno .

+9

test1=function(){
  l=list()
  for(i in 1:10000){
    l=append(l,"abc")
  }
  return(l)
}
system.time(test1()) # 2.367 sec

test2=function(){
  l=vector("list", 10000)
  for(i in 1:10000){
    l[i]="abc"
  }
  return(l)
}
system.time(test2()) # 0.015 sec

test3=function(){
  l=list()
  for(i in 1:10000){
    l[i]="abc"
  }
  return(l)
}
system.time(test3()) # 0.309 sec

test4=function(){
  return(lapply(1:10000, function(x) "abc"))   
}
system.time(test4()) # 0.003

R :)

, , lappy

+2

Source: https://habr.com/ru/post/1542127/


All Articles