I am trying to create a list 1000 entries long where each entry of the list a random vector. In this case the vector should be a 10 integers chosen from the integers 1 to 100. I want to avoid doing this in a loop.
If I run the following, this does not sample again, but just replicates the sample across all 1000 entries of the list:
list.of.samples <- rep(list(sample(1:100,size=10)),1000)
Is there an easy way that I am missing to vectorize the generation of these 1000 samples and store them in a list?
In cases like this, I often use the replicate
function:
list.of.samples <- replicate(1000, sample(1:100,size=10), simplify=FALSE)
It repeatedly evaluates its second argument. Setting simplify=FALSE
means you get back a list, not an array.
rep
will repeat whatever is given. lapply
should do what you want.
list.of.samples = lapply(1:1000, function(x) sample(1:100,size=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