[R] Randomly remove condition-selected rows from a matrix

Guillaume Chapron carnivorescience at gmail.com
Tue Dec 30 15:59:02 CET 2008


Hello all,

I create the following matrix:

m <- matrix(1:20, nrow = 10, ncol = 2)

which looks like:

       [,1] [,2]
  [1,]    1   11
  [2,]    2   12
  [3,]    3   13
  [4,]    4   14
  [5,]    5   15
  [6,]    6   16
  [7,]    7   17
  [8,]    8   18
  [9,]    9   19
[10,]   10   20

Then, I want to remove randomly 2 rows among the ones where m[,1]<8  
and m[,2]>12

I suppose the best way is to use the sample() function. I understand  
how to do it when I remove among any rows, but I have not been able to  
do it when I remove among specific rows only. What I could do is split  
the matrix into two matrices, one with the rows to be sampled and  
removed, one with the other rows. I would sample and remove, and then  
merge the two matrices again. But since this part of the code is going  
to be done many times, I would like to have it the most efficient  
possible without creating new objects. Any idea? Thanks!

Cheers

Guillaume



More information about the R-help mailing list