I'm attempting to prepare a demonstration in R of how the repeated stratified random sampling of a small population results in a near-normal sampling distribution of means. As an example consider the R code below (which works but is very slow due to looping).
#Dummy population made up of dice throws - 18 per row
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P1 <- as.data.frame(c(5,6,5,1,6,4,2,2,4,4,6,6,5,2,3,5,1,6))
P1$Zn <- 1
names(P1) <- c('Die','Zn')
Dt <- P1
P2 <- as.data.frame(c(2,5,4,5,5,5,3,3,2,5,6,1,2,5,4,3,6,1))
P2$Zn <- 2
names(P2) <- c('Die','Zn')
Dt <- rbind(Dt,P2)
# Empty dataframe to hold random draws
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Smps <- data.frame(Die = numeric(), Zn= numeric(),Drw = numeric())
# Draw stratifed samples one from each row
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print(paste('Start','at',Sys.time()))
n <- 10000 # number of draws
r <- 2 # number of rows (the strata)
for (j in 1:n){
# for a 2 strata
for (i in 1:r){
#sub set strata
x <- subset(Dt, Dt$Zn == i)
# random sample
y <- x[sample(1:18,1),]
y$Drw <- j
#append sample
Smps <- rbind(Smps,y)
}
# report progress
if(right(j,3) == '000'){
print(paste(j,'at',Sys.time()))
flush.console()
}
}
# Compute the sample means
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mns <-aggregate(Smps[, 1], list(Smps$Drw), mean)
# Density plot of means
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
d <- density(Mns$x)
plot(d,xlab = 'Means', las=1, main = '')
polygon(d, col="blue", border="blue")
I'm expecting there is an R package with a function that does this type of stratified sampling but I am struggling to find the one that works in the manner I can understand. Something that inputs a data frame with a grouping field and the number of samples to be drawn from each group is something I'm expecting has already been written to allow a repeat sampling by a group. Any pointers to examples that work would be appreciated. Ideally, I would like to prepare to say 100,000 stratified samples from a known population with many more strata and then plot the distribution of the means (but quickly)