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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With