[Rd] rmultinom() -- how \\ via own C code?

Martin Maechler Martin Maechler <maechler@stat.math.ethz.ch>
Mon Jan 27 14:43:10 2003

I've had a need for multinomial "random number generation"
occasionally. And other people too.
The following code is currently in the 
(very small ``not very high importance'') CRAN package normix
 --- which I will rename to "nor1mix" very seen because of a 
    ``name registration'' problem

I want to add "this" (well the functionality) to a standard
package -- "mva" probably.

The reason for my post is to ask about importance for C code
(and a an official API to that).  
1) I think we have no clear precedence of a C interface to
   **multivariate** random numbers, and
2) It might be of too marginal importance.

If you (discussants) conclude that a C interface is not at all
desired, I consider using the R code as it is now -- which is
not optimal --- and most importantly:
If this should ever be changed, the change would hardly be
In other words, calling the not-yet existing C interface would
produce different random numbers... 


- Opinions ?

- Is there already C code around to do this ``in one step'' ?

Martin Maechler <maechler@stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><

## This is based on rmultz2() from S-news by Alan Zaslavsky & Scott Chasalow;
## in R available from library(combinat) -- but it has
## Arg.names like  rbinom();  returns  n x p matrix
rmultinom <- function(n, size, prob) {

    K <- length(prob) # #{classes}
    matrix(tabulate(sample(K, n * size, repl = TRUE, prob) + K * 0:(n - 1),
                    nbins = n * K),
           nrow = n, ncol = K, byrow = TRUE)