# SV: [R] sample from contingency table

Regin Reinert Regin.Reinert at gallup.dk.tnsofres.com
Wed Sep 20 08:53:20 CEST 2000

```I have had the same problem and I wrote this function

rmulti <- function(n, size, p)
{
NrDim <- length(p)
if(NrDim<2) stop("The simulated variabel has to be at least
2-dimensional")
res <- matrix(data=NA, nrow=n, ncol=NrDim)
p <- p/sum(p)
TempSize <- size
for(i in 1:NrDim)
{
TempP <- p[i]/sum(p[i:NrDim])
TempBin <- rbinom(n=n, size=TempSize, prob=TempP)
TempSize <- TempSize-TempBin
res[,i] <- TempBin
}
return(res)
}

# Then you can draw 10 samples like this, whith
# each row representing a contingency table

x <- as.matrix(1:4, nrow=2, ncol=2)
rmulti(10, sum(x), x)

Regin

-----Oprindelig meddelelse-----
Fra: Dirk F. Raetzel [mailto:raetzel at Mathematik.Uni-Marburg.de]
Sendt: 19. september 2000 18:48
Til: R-Help Mailing List
Emne: [R] sample from contingency table

Hello,

I have a multivariate (dim >= 3) discrete distribution
given by a contingency table from which I want to draw independent
random samples. The result should be a data.frame (or array) with each
column representing a dimension.

Before starting to hack some search tree with approbiate
transformations: Is there any built-in function I
have overseen or did anybody program such a function already?

Dirk

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
_._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```