Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate list with same object efficiently

Suppose I have some object (any object), for example:

X <- array(NA,dim=c(2,2))

Also I have some list:

L <- list()

I want L[[1]], L[[2]], L[[3]],...,L[[100]],...,L[[1000]] all to have the object X inside it. That is, if I type into the console L[[i]], it will return X, where i is in {1,2,...,1000}.

How do I do this efficiently without relying on a for loop or lapply?

like image 398
Jase Avatar asked Jul 21 '13 10:07

Jase


People also ask

How do I create a list with the same value?

Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 . The result of the expression will be a new list that contains the specified value N times. Copied!

Which is more efficient list or set?

Sets use hashing to perform look ups which makes them way faster than lists in this regard. (In the practical example the code using lists took about 45 seconds to run, whereas the code with sets took less than a tenth of a second!)

Is array more efficient than list?

Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.


2 Answers

Make a list of 1 and replicate it.

L <- rep(list(x), 1000)
like image 130
Hong Ooi Avatar answered Oct 22 '22 20:10

Hong Ooi


Using replicate even if it still a kind of a loop solution:

L <- replicate(1000,X,simplify=FALSE)

EDIT benchmarkking the 2 solutions :

X <- array(NA,dim=c(2,2))
library(microbenchmark)
microbenchmark( rep(list(X), 10000),
               replicate(10000,X,simplify=FALSE))

                              expr      min       lq    median        uq      max neval
                  rep(list(X), 10000) 1.743070 2.114173  3.088678  5.178768 25.62722   100
replicate(10000, X, simplify = FALSE) 5.977105 7.573593 10.557783 13.647407 80.69774   100

rep is 5 times faster. I guess since replicate will evaluate the expression at each iteration.

like image 5
agstudy Avatar answered Oct 22 '22 18:10

agstudy