[R] Generate Binary Matrix

ken knoblauch ken.knoblauch at inserm.fr
Wed Apr 9 23:16:31 CEST 2014


Doran, Harold <HDoran <at> air.org> writes:
> I am trying to generate a binary matrix where 
 row 
in the matrix is guaranteed to have at 
least one 1.
> Ideally, I would like most rowSums  to be equal 
 2 or 3 
with some 1s and some 4s. But, 
rowSums cannot be equal
> to 0.
> 
> I can tinker with the vector of probability weights, 
but in 
 so (in the way I am doing it) this 
causes for
> more rowSums to be equal to 4 than I ideally would 
, but this never helps to guarantee a 
rowSum will not be
> equal to 0. I could post-hoc tinker with any rows 
 are all 
0, but seems like that may be just 
inefficient.
> 
> Below is sample code, any ideas on how to best 
tackle this?
> 
> Harold
> 
> dimMat <- matrix(0, 1000, 4)
> for(i in 1:1000){
>     dimMat[i, ] <- sample(c(0,1), 4, replace = TRUE, prob = c(.3, .7))
>                 }
> 
> table(rowSums(dimMat))


Wht don't you sample from the distribution of row sums 
for each row and then distribute that many 1's randomly
among the columns.

Ken




More information about the R-help mailing list