Skip to content
Prev 278780 / 398502 Next

fill binary matrices with random 1s

Folks:
On Tue, Nov 29, 2011 at 6:24 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
This is unnecessary. In R: matrices are simply vectors with a "dim"
attribute, so you can treat them as vectors:

mat[sample(nrow(mat)*ncol(mat),1] <- 1

Moreover, this also suggests a simple way to do this sequentially:
Simply create your vector of random indices at one go and use it for
your loop -- no checking on what previously was sampled is necessary:

ransamp <- sample(100,100)  ## assuming nrow = ncol = 10

for( i in 1:100) {
  mat[ransamp[i]] <- 1
## do whatever you want
}

HTH

Cheers,
Bert