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?
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!
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!)
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.
Make a list of 1 and replicate it.
L <- rep(list(x), 1000)
                        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.
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