Skip to content

rmultinom

1 message · Ravi Varadhan

#
Hi Mark:

I had also used sample and tabulate for generating multinomial and found it
to be quite slow.  So I had written a multinomial random numbers generator
based on the GENMUL subroutine from "ranlib", which in turn is based on the
algorithm from Luc Devroye's book on "Non-Uniform Random Variate Generation"
You may want to compare this with your hybrid algorithm and see their
relative performance.

Best,
Ravi.

###############################################################
##      A multinomial random vector generator
rmultinom <- function(n, p){
 ncat <- length(p)
#     Check Arguments
      if (n < 0) {cat("n < 0 ","\n"); break}
      if (ncat <= 1) {cat("ncat <= 1 ","\n"); break}
      if (any(p < 0.0)) {cat("Some P(i) < 0 ","\n"); break}
      if (any(p > 1.0)) {cat("Some P(i) > 1.0 ","\n"); break}
 eps <- .Machine$double.eps^0.9
      if (sum(p) > (1.0 + eps) | sum(p) < (1.0 - eps) ) {cat("Sum of P(i)
should equal 1.0 ","\n"); break}

#     Initialize variables
      ntot <- n
      sum <- 1.0
      ix <- rep(0,ncat)

#     Generate the observation
      for (icat in 1:(ncat - 1)) {
          prob <-  p[icat]/sum
          ix[icat] <-  rbinom(1,ntot,prob)
          ntot <- ntot - ix[icat]
          if (ntot <= 0) return(ix)
          sum <- sum - p[icat]
 }
      ix[ncat] <- ntot
 return (ix)
}

-----Original Message-----
From: Mark.Bravington at csiro.au <Mark.Bravington at csiro.au>
To: r-help at stat.math.ethz.ch <r-help at stat.math.ethz.ch>
Date: Wednesday, August 07, 2002 11:16 PM
Subject: [R] RE: rmultinom
wish
"%upto%"
.-.-
._._

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._