Search code examples
rvectorrandomsampling

How to shuffle from a vector in R?


Suppose that we have the following vector that could change within a loop but with fixed length:

V = c(8,15,16,7,3)

I need to shuffle in each iteration m compenents at uniform from V. ( 1<=m<=5 & m is integer)

Then I will need to store those components in their respective positions at another vector K with the same length as V. The other positions will simply contain the value 0.

For example: let j be the current iteration and let assume that V will not change. some possible results could be :

m=3
---------------------
//
j=1
V= c(8,15,16,7,3)
K= c(0,15,0,7,3)   # 3 numbers are shuffled //


//
j=2
V= c(8,15,16,7,3)
K= c(8,0,0,7,3)   # 3 numbers are shuffled
 //
.
.
.

j=4
V= c(8,15,16,7,3)
K= c(0,0,16,7,3)   # 3 numbers are shuffled

I wish my question and the desired output is clear. Thank a you a lot for help!


Solution

  • This is a very rough solution, but it should answer your question.

    # initialization of parameters
    V = c(8, 15, 16, 7, 3)
    m = 3    
    n_iter = 10
    mat <- matrix(0, nrow = n_iter, ncol = length(V))
    
    # creation of matrix
    set.seed(42)
    for (j in 1:n_iter)
      mat[j,] <- replace(V, sample(5, 2), 0)
    

    Output

     #       [,1] [,2] [,3] [,4] [,5]
     #  [1,]    8   15    0    0    3
     #  [2,]    8    0   16    0    3
     #  [3,]    8   15    0    7    0
     #  [4,]    0   15   16    7    0
     #  [5,]    8   15    0    7    0
     #  [6,]    0   15   16    0    3
     #  [7,]    8   15   16    0    0
     #  [8,]    8    0   16    0    3
     #  [9,]    8   15    0    0    3
     # [10,]    8    0   16    7    0