[R] sample "n" random positions from a matrix

Charles C. Berry cberry at tajo.ucsd.edu
Mon Dec 11 05:00:57 CET 2006


On Sun, 10 Dec 2006, Milton Cezar Ribeiro wrote:

> Hi there,
>
>  I have a binary matrix (dim 100x100) filled with values 0 and 1. I need
>  select a record "n" positions of that matrix when values are 1. How can
>  I do that?
>

Is this what you want?

> mat.100 <- diag(100) # just for instance
> n <- 7  # supposing you want 7
> which( mat.100==1, arr.ind=T )[ sample( 100, n ), ]
      row col
[1,]  99  99
[2,]  93  93
[3,]  36  36
[4,]  74  74
[5,]  11  11
[6,]   3   3
[7,]  21  21
>

[...]

Charles C. Berry                        (858) 534-2098
                                          Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0717




More information about the R-help mailing list