[R] Generate Binary Matrix
David Carlson
dcarlson at tamu.edu
Wed Apr 9 23:33:10 CEST 2014
You could randomly assign 1 to a single column in each row and
then use binomial draws on the remaining 0's:
> set.seed(42)
> dimMat <- matrix(0, 1000, 4)
> dimMat[cbind(1:1000, sample.int(4, 1000, replace=TRUE))] <- 1
> dimMat[dimMat<1] <- sample(0:1, 3000, replace=TRUE, prob=c(.6,
.4))
> table(rowSums(dimMat))
1 2 3 4
217 402 310 71
> colSums(dimMat)
[1] 551 586 533 565
> sum(dimMat)
[1] 2235
-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352
-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of Doran, Harold
Sent: Wednesday, April 9, 2014 3:56 PM
To: r-help at r-project.org
Subject: [R] Generate Binary Matrix
I am trying to generate a binary matrix where every row in the
matrix is guaranteed to have at least one 1. Ideally, I would
like most rowSums to be equal to 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
doing so (in the way I am doing it) this causes for more rowSums
to be equal to 4 than I ideally would like, but this never helps
to guarantee a rowSum will not be equal to 0. I could post-hoc
tinker with any rows that 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))
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible
code.
More information about the R-help
mailing list