Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, is growing a list just as inefficient as growing a vector?

Tags:

r

some_list <- list()

for (i in 1:1000) {
    some_list[[i]] <- i
}

I am wondering if this is just as inefficient had some_list been a vector instead.

like image 222
Big Cat Public Safety Act Avatar asked Dec 10 '18 19:12

Big Cat Public Safety Act


People also ask

How does a vector differ from a list R?

A list holds different data such as Numeric, Character, logical, etc. Vector stores elements of the same type or converts implicitly. Lists are recursive, whereas vector is not. The vector is one-dimensional, whereas the list is a multidimensional object.

Is vector in R like a list?

A list is actually still a vector in R, but it's not an atomic vector. We construct a list explicitly with list() but, like atomic vectors, most lists are created some other way in real life.


1 Answers

The answer seems to be 'yes'. You can benchmark it.

f = function() {
  some_list <- list()
  for (i in 1:100000)
    some_list[[i]] <- i
}

g = function() {
  some_vector <- c()
  for (i in 1:100000)
    some_vector[i] <- i
}

h = function() {
  some_list <- vector("list", 100000)
  for (i in 1:100000)
    some_list[[i]] <- i
}

k = function() {
  some_vector <- integer(100000)
  for (i in 1:100000)
    some_vector[i] <- i
}

microbenchmark::microbenchmark(f(), g(), h(), k(), times = 10)
Unit: milliseconds
 expr       min        lq      mean    median        uq      max neval
  f() 27.723670 28.058052 31.043727 28.812197 33.973669 38.58484    10
  g() 20.699626 21.235849 23.029765 21.531695 26.419720 28.04681    10
  h()  7.056399  7.151585  7.887856  7.356198  7.936945 10.80190    10
  k()  6.025570  6.076456  7.194970  6.408183  7.808957 11.00644    10
like image 172
JRR Avatar answered Oct 23 '22 04:10

JRR