How to write a function that demonstrates a central limit theorem with graphics

I am trying to write a function that creates animated graphics (without using an animation package) where users can control inputs (sample size and ect ...), which demonstrates a central limit theorem. This is what theoretically I would like, but had problems writing a function in which users can actually control the inputs, as I mentioned above.

msample <- NA # set up empty vector
ns <-3 # sample size
for(i in 1:500){
sam <- runif(ns) * 10 # draw sample
 msample[i] <- mean(sam) # save mean of sample
h <- hist(msample, breaks=seq(0,10, len=50), # histogram of all means
xlim=c(0,10), col=grey(.9),
xlab="", main="Central Limit Theorem", border="blue", las=1)
points(sam, rep(max(h$count), length(sam)),
pch=16, col=grey(.2)) # add sampled values
points(msample[i], max(h$count), # add sample mean value
col="red", pch=15)
text(10, max(h$count), paste("sample no", i))
hist(msample[i], breaks=seq(0,10, len=50), # ovelay sample mean 
xlim=c(0,10), col="red", add=T, # in histogram
xlab="", border="white", las=1)
Sys.sleep(.05)
}
+5
source share
1 answer

It is not clear what you want as a result. but I think you can put the code in a function and use the dot argument ...as a solution to provide additional parameters (e.g. distribution parameters).

   central.simul <- function(N, ns,type = c("runif", "rnorm", "rbinom"),...){
        type <- match.arg(type)
        msample <- rep(NA,N)  ## EDIT here: intialisation
        for(i in 1:N){
          sam <- switch(type,
                        runif = runif(ns)*10,
                        rnorm = rnorm(ns)*10,
                        rbinom = rbinom(ns,...))
          msample[i] <- mean(sam) # save mean of sample
          add.hist <- i > 1
          h <- hist(msample, breaks=seq(0,10, len=50), # histogram of all means
                    xlim=c(0,10), col=grey(.9),
                    xlab="", main="Central Limit Theorem", border="blue", las=1,add=add.hist)
          points(sam, rep(max(h$count), length(sam)),
                 pch=16, col=grey(.2)) # add sampled values
          points(msample[i], max(h$count), # add sample mean value
                 col="red", pch=15)
          text(10, max(h$count), paste0("sample no ", i))
          hist(msample[i], breaks=seq(0,10, len=50), # ovelay sample mean 
               xlim=c(0,10), col="red", add=T, # in histogram
               xlab="", border="white", las=1)
          Sys.sleep(.1)
        }
    }

, :

central.simul(10,3,'runif')
central.simul(10,3,'rbinom',size=2,prob=0.5)

, rnorm, ( , ), .

+2

All Articles