简体   繁体   中英

Multiple different random samples in R

I'm new to R and I've got a question:

choice <- c(TRUE, FALSE, FALSE, FALSE)
rep(sample(choice, size = 4, replace=FALSE), times = n)

always repeats the same vector, eg (FALSE, TRUE, FALSE, FALSE)

However, I want to have n different random samples of the vector choice in a new vector (replace must be FALSE, because only 1 in 4 elements should be TRUE).

Which function should I choose? I'm not allowed to use for-loops.

You can use replicate . It returns a matrix, which you can then turn into a vector.

choice <- c(TRUE, FALSE, FALSE, FALSE)
n <- 3
set.seed(42) # for reproducibility
as.vector(replicate(n, sample(choice, size = 4, replace=FALSE)))
#[1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM