Reputation: 3330
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?
Upvotes: 7
Views: 4747
Reputation: 1424
To create a vector with letters:
library(wakefield)
c = lower(10, k=3) # generates 10 random letters from the first 3
c
#> "b" "a" "a" "a" "a" "b" "c" "b" "a" "b"
Upvotes: 0
Reputation: 511
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.
Upvotes: 12
Reputation: 6345
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))
Upvotes: 3