Skip to content
Prev 277052 / 398506 Next

Listing tables together from random samples from a generated population?

Hi:

There are two ways you could go about this: lists or arrays. It's
pretty easy to generate an array, a little more work to get the list.
I'm assuming the objective is to extract a chi-square statistic from
each table, so I'll show a couple of ways to do that, too.

library('plyr')

## Start with the data:
y<-data.frame(gender=sample(c('Male', 'Female'), size=100000,
                                            replace=TRUE, c(0.5, 0.5)),
                     tea=sample(c('Yes', 'No'),  size=100000,
                                        replace=TRUE, c(0.5, 0.5)))
## Function to produce a table:
tabfun <- function(d) table(d[sample(seq_len(nrow(d)), 100), ])
x2stat <- function(m) chisq.test(m)$statistic

## Array version:

tbarr <- replicate(100, tabfun(y))
# X^2 statistics using apply() from base R and
# aaply() from plyr:
u1 <- apply(tablist, 3, x2stat)
u2 <- aaply(tablist, 3, x2stat)

## List version:

tblst <- vector('list', 100)
for(i in seq_along(tblst)) tblst[[i]] <- tabfun(y)

v1 <- unname(do.call(c, lapply(tblst, x2stat)))
v2 <- laply(tblst, x2stat)
HTH,
Dennis
On Thu, Nov 10, 2011 at 12:48 PM, Simon Kiss <sjkiss at gmail.com> wrote: