Home > front end >  Sample without replacement x number of times from a vector
Sample without replacement x number of times from a vector

Time:12-11

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)).

CodePudding user response:

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

CodePudding user response:

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)
  •  Tags:  
  • r
  • Related