gen*_*iva 5 animation r function
我正在尝试编写一个创建动画图形的函数(不使用动画包),用户可以在其中控制演示中心极限定理的输入(样本大小和分布等).理论上这就是我想要的,但是如上所述,在编写用户可以实际控制输入的功能方面遇到了麻烦.
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)
}
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚您想要什么结果。但我认为,您可以将代码放入函数中,并使用点参数 ...作为提供额外参数(例如分布参数)的解决方案。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方式调用它:
central.simul(10,3,'runif')
central.simul(10,3,'rbinom',size=2,prob=0.5)
Run Code Online (Sandbox Code Playgroud)
例如,该代码不适用于 rnorm (我认为您应该修改中断),但这应该是一个好的开始。
| 归档时间: |
|
| 查看次数: |
925 次 |
| 最近记录: |