[R] Re: [S] Multinomial

Martin Maechler maechler at stat.math.ethz.ch
Mon Aug 5 12:02:30 CEST 2002

>>>>> "Jacob" == Jacob van Wyk <jlvw at rau.ac.za> writes:

    Jacob> Could anybody please help: I simply want to generate
    Jacob> random samples from a multinomial distribution with
    Jacob> fixed n and given probability vector p.

    Jacob> How can I do this?

I've recently written the following {for the R package "normix"}.  
The above is really a FAQ.
I think I'd propose to adopt this (or an improvement of it) both
for R and S-plus :

  ## This is based on rmultz2() from S-news by Alan Zaslavsky & Scott Chasalow
  ## {and adapted from the R package "combinat"}.
  ## 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)

Martin Maechler <maechler at 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			<><
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

More information about the R-help mailing list