Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of random vectors in R

Tags:

random

r

vector

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?

like image 351
Michael Discenza Avatar asked Feb 04 '14 00:02

Michael Discenza


2 Answers

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.

like image 61
pteetor Avatar answered Sep 28 '22 07:09

pteetor


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))
like image 22
sharoz Avatar answered Sep 28 '22 05:09

sharoz