# [R] Generate Binary Matrix

Clint Bowman clint at ecy.wa.gov
Wed Apr 9 23:29:35 CEST 2014

```A bit kludgey but how about:

dimMat <- matrix(0, 1000, 4)
for(i in 1:1000){
while(sum(dimMat[i, ] <- sample(c(0,1), 4, replace = TRUE, prob = c(.3, .7)))==0) dimMat[i, ] <- sample(c(0,1), 4, replace = TRUE, prob = c(.3, .7))
}
table(rowSums(dimMat))

Clint Bowman			INTERNET:	clint at ecy.wa.gov
Air Quality Modeler		INTERNET:	clint at math.utah.edu
Department of Ecology		VOICE:		(360) 407-6815
PO Box 47600			FAX:		(360) 407-7534
Olympia, WA 98504-7600

USPS:           PO Box 47600, Olympia, WA 98504-7600
Parcels:        300 Desmond Drive, Lacey, WA 98503-1274

On Wed, 9 Apr 2014, ken knoblauch wrote:

> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help