SV: [R] sample from contingency table

Dirk F. Raetzel raetzel at Mathematik.Uni-Marburg.de
Wed Sep 20 11:41:58 CEST 2000


On Today, Bill Venables wrote:

> Hey, hang on...  If I have understood the original question properly
> what you have to do is to sample from the cells of a contingency table
> with probabilities proportional to the frequencies in those cells.
> Here is the original question:
yes.

> I can't see why you would need a "search tree" for this problem
> either.  Here is (what I think is) a very simple solution:
well: if there wouldn't have been an easy way to do it, I would have
followed the suggestions of 'Ripley, Stochastic Simulation, 3.3 Discrete
distributions' ...

> sampct <- function(n, Fr) {
> # sample with replacement from a multivariate distribution
> # defined by a contingency table
>   if(!is.null(dfr <- dimnames(Fr)) &&
>      prod(sapply(dfr, length)) == length(Fr))
>     dfr <- expand.grid(dfr)
>   else
>     dfr <- expand.grid(lapply(dim(Fr), seq))
>   dfr[sample(1:nrow(dfr), n, prob = Fr, rep = T), ]
> }
This is exactly what I was looking for: Both from the result and from the
clever way of programming it. [Even so using sample() quite often, I did
not see the (a posteriori) obvious connection] 

Thanks,

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



More information about the R-help mailing list