简体   繁体   中英

Sample without replacement x number of times from a vector

I have a vector c(1,2,3,4,5,6,7,8,9,10,11) . I want to draw a sample of N = 2, 5 times from this vector without replacement; I would like to save the results from each selection in a separate column. The output could look like this: structure(c(1, 2, 3, 9, 7, 10, 4, 8, 5, 6), dim = c(2L, 5L)) .

matrix with two rows and five columns.

matrix(sample(x), nrow=2, ncol=5)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    5    7    4    8    2
# [2,]    3   10    9    1    6

Something like the following:

set.seed(7*11*13)
x <- c(1,2,3,4,5,6,7,8,9,10,11)

result <-matrix(as.numeric(NA), 2, 5)

for (i in 1:5) result[,i] <- 
     sample(x, 2, replace=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