Search code examples
rsamplerep

Duplicating rows in R matrix


I have a small matrix, say

x <- matrix(1:10, nrow = 5) # values 1:10 across 5 rows and 2 columns

The result is

     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

What I want to be able to do now is duplicate random rows in x; for example, producing

     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    5   10
[4,]    4    9 
[5,]    5   10

I believe the R function 'rep()' is the solution and also 'sample()', but I don't want to have to specify the size argument in sample(); i.e., I want an arbitrary number of rows to be duplicated each time.

Is there a simple way of accomplishing this using rep() and sample()?


Solution

  • We can use the sample function. I've used set.seed for reproducibility, if you remove that line the results should change.

    set.seed(1848) # reproducibility
    x[sample(x = nrow(x), size = nrow(x), replace = T), ]
    
         [,1] [,2]
    [1,]    1    6
    [2,]    2    7
    [3,]    5   10
    [4,]    1    6
    [5,]    5   10