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

Guillaume Chapron carnivorescience at gmail.com
Wed Dec 31 18:44:54 CET 2008


> I believe this does what you want:
>
> m[-sample(which(m[,1]<8 & m[,2]>12),2),]
>
> Analysis:
>
> Get a boolean vector of rows fitting criteria:
>    m[,1]<8 & m[,2]>12
>
> What are their indexes?
>    which(...)
>
> Choose two among those indexes:
>     sample(...,2)

Thanks, but this does not seem to always work.

Supposing I sample only one row among the ones matching my criteria.  
Then consider the case where there is just one row matching this  
criteria. Sure, there is no need to sample, but the instruction would  
still be executed. Then if this row index is 15, my instruction  
becomes which(15,1), and this can gives me any row from 1 to 15, which  
is not correct. I have to make a condition in case there is only one  
row matching the criteria.



More information about the R-help mailing list