2013-04-18 21 views
5

我想写一个函数,创建动画图形(不使用动画包),用户可以控制输入(样本大小和分布等.. )证明了中心极限定理。这在理论上是我想要的,但是在编写用户可以实际控制输入的功能时遇到问题,正如我上面提到的那样。如何写一个函数,演示中心极限定理与图形

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) 
} 
+0

什么不适合你?期望的结果是什么? – 2013-04-18 05:27:43

+0

+1为好的教育例子。我想你正在寻找'readline()'函数。只是不要忘记做一些输入验证。 – 2013-04-18 06:01:12

+0

@RomanLuštrik期望的结果就是具有用户可以控制输入的整体功能。 – 2013-04-19 17:18:23

回答

2

你不清楚你想要什么结果。但我认为,您可以将代码放入函数中,并使用点参数...作为给出额外参数(例如分布参数)的解决方案。

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例如工作的代码(你应该修改休息,我认为),但它应该是一个良好的开端。

+0

谢谢,但是当运行你实现的代码,并调用central.simul,因为你建议我得到以下错误错误“msample [i] < - 意味着(山姆):对象'msample'未找到” – 2013-04-18 19:20:20

+0

@geneteics_diva我编辑我的答案。我忘记初始化masample矢量。 – agstudy 2013-04-18 21:31:07

+0

再次感谢,我正在削减,因为某些原因,它仍然无法正常工作: - / – 2013-04-19 01:48:09

相关问题