Reputation:
How can i generate 1000 samples with size 8 from a vector containing 20 elements in R. How can i make a single sample a thousand? please help
Upvotes: 0
Views: 266
Reputation: 8064
I think using *apply
family is better than using a for
loop as R
is vectorized.
Below is a code that even work on multicore
X=1:20
# on linux
library(parallel)
library(magrittr)
mclapply(rep(list(X), 1000), sample, 8, replace = TRUE, prob = NULL) %>%
simplify2array
# on windows
cl <- makeCluster(detectCores()) # type = "MPI" / type = "PSOCK"
parLapply(cl, rep(list(X), 1000), sample, 8, replace = TRUE, prob = NULL) %>%
simplify2array
stopCluster(cl)
Upvotes: 0
Reputation: 175
If X is the vector containing your 20 elements, the you can use:
sample(X, 8, replace = TRUE, prob = NULL)
Loop this statement 1000 times as below:
Results <- matrix(, nrow = 1000, ncol = 8)
X=1:20
for (i in 1:1000){
Results[i, ]<-sample(X,8,replace=TRUE,prob=NULL)
}
Each row in the matrix called Sample should now represent each of your 1000 samples.
Upvotes: 2