Creating random binary matrices in R

Reading this post http://dirk.eddelbuettel.com/blog/2012/09/02/#faster_binomial_matrix_creation I wondered if a solution in pure R could not be further improved. It turns out it could; here is my solution (compared with david, the best pure-R solution in the blog post):

n <- 500
k <- 100

david <- function(m, n)
    matrix(sample(0:1, m * n, replace = TRUE), m, n)

f <- function(m, n) {
    tmp <- sample.int(2L, size = m * n, replace = TRUE) - 1L
    dim(tmp) <- c(m, n)
    tmp
}

set.seed(243)
example1 <- david(n,k)
set.seed(243)
example2 <- f(n,k)
all.equal(example1, example2)
      
[1] TRUE
      

Comparing running times, the new function f gives a speedup of about 50%.

system.time(for (i in 1:1000) david(n,k))
system.time(for (i in 1:1000) f(n,k))
      
   user  system elapsed 
  1.100   0.000   1.101
   user  system elapsed 
  0.684   0.000   0.684
      

return to main page...

return to R page...