Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 is to create a data frame of the N random samples or randomly selected permutations.

I have tried the following:

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

Since there are so many possible permutations, I would receive an error message.

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 sapply() with sample(). However, I don't think this approach is that efficient.

I have also tried:

samples <- replicate(100, table(sample(1:663, 663,replace = F))) 

but I just get a data frame with 100 columns of ones.

like image 254
RTrain3k Avatar asked Feb 05 '17 03:02

RTrain3k


People also ask

How do you generate a random sample in R?

For example if we want to generate random numbers from 3 to 10 and we want to generate random numbers 8 times that is 8 results, then we can make use of predefined sample() function in R as follows, > sample(3:10, 8, replace = TRUE)


1 Answers

replicate will work

a <- 1:663 #vector of 663 elements
perms <- as.data.frame(replicate(100, sample(a)))
like image 101
radek Avatar answered Nov 10 '22 00:11

radek