[R] sample "n" random positions from a matrix
Charles C. Berry
cberry at tajo.ucsd.edu
Mon Dec 11 05:04:40 CET 2006
On Sun, 10 Dec 2006, Charles C. Berry wrote:
> 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
OOPS! That only works when there is exactly one one in each row. This is
what is needed generally:
> index.of.ones <- which(mat.100==1,arr.ind=T)
> index.of.ones[ sample( nrow( index.of.ones ), n ), ]
row col
[1,] 82 82
[2,] 36 36
[3,] 54 54
[4,] 89 89
[5,] 88 88
[6,] 52 52
[7,] 65 65
>
>>
>
> [...]
>
> 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
>
>
>
>
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