r - how to to write a function that demonstrates the central limit theorem with graphics -
i'm trying write function creates animated graphics(without using animation package) users can control inputs(sample size , distribution ect..) demonstrates central limit theorem. in theory want having trouble writing function users can control inputs mentioned above.
msample <- na # set 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 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) }
it not clear want result. think, can put code in function , use dot argument ...
solution give parameters (distribution parameters example).
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 <- > 1 h <- hist(msample, breaks=seq(0,10, len=50), # histogram of 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) } }
you can call using :
central.simul(10,3,'runif') central.simul(10,3,'rbinom',size=2,prob=0.5)
the code don't work rnorm example ( should modify breaks think), should start.
Comments
Post a Comment