RTrain3k RTrain3k - 4 years ago 207
R Question

How to draw N random samples from a vector in R?

I have a vector with 663 elements. I would like to create random samples from the vector equal to the length of the vector (i.e. 663). Said differently, I would like to take random samples from all possible orderings of the 663 elements. My goal would be to create a data frame of the N random samples or randomly selected permutations.

I've tried

perms <- as.data.frame(permn(1:663))

but since there is so many possible permutations I receive an error.

My next idea would be to create a data frame with as many rows as I would like samples/permutations and as many variables as elements (i.e. 663) and use a function like
. But I don't think that is that efficient.

I've also tried
samples <- replicate(100, table(sample(1:663, 663,replace = F)))
but I just get a data frame with 100 columns of ones.

Answer Source

replicate will work

a <- 1:663 #vector of 663 elements
perms <- as.data.frame(replicate(100, sample(a)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download