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

Sarah Goslee sarah.goslee at gmail.com
Tue Dec 30 16:08:21 CET 2008


Assuming your values aren't always in such neat order, you could use
something like:

valtoremove1 <- sample((1:nrow(m))[m[,1] < 8], 1)
valtoremove2 <- sample((1:nrow(m))[m[,1] > 12], 1)

Sarah

On Tue, Dec 30, 2008 at 9:59 AM, Guillaume Chapron
<carnivorescience at gmail.com> wrote:
> 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



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list