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)
}
4

1 回答 1

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(我认为您应该修改中断),但这应该是一个好的开始。

于 2013-04-18T07:52:53.683 回答