Random choice of rows in an array in R

3

I have a problem that gives me a numeric matrix mxn where m is the number of observations (row) and n the number of variables (column). I need to randomly choose p rows (p < m) without replacement from that array. So I will create a p x n matrix with which I will perform some calculations. How can I do this ??

    
asked by anonymous 17.04.2018 / 03:04

1 answer

3

To randomly select p numbers from m , the easiest way is to use the sample function.

set.seed(1234)    # Faz os resultados reprodutíveis

m <- 7
mat <- matrix(rnorm(35), nrow = m)

p <- 4
inx <- sample(nrow(mat), p)
sub_mat <- mat[inx, ]
sub_mat
#           [,1]        [,2]       [,3]       [,4]       [,5]
#[1,] -1.2070657 -0.54663186  0.9594941 -0.4906859 -0.0151383
#[2,]  0.5060559 -0.77625389  2.4158352  0.5747557 -0.5012581
#[3,] -0.5747400  0.06445882  0.1340882 -1.0236557 -1.6290935
#[4,] -2.3456977 -0.47719270 -0.9111954 -0.6937202 -0.4755931
    
17.04.2018 / 07:09