R: 信賴區間(Confidence Intervals) 動態 Demo

前陣子在教統計學的信賴區間,想找一些可以動態 demo 信賴區間的 R 程式或套件,但都不甚滿意,所以自己寫了一個

 

?View Code LANGUAGE
################################################################### 
# CI
###################################################################
###############################
# Configuration
###############################
# n = sample size
n = 30
# nCI = number of confidence intervals
nCI = 100
 
mu = 60
xsd = 10
 
# Confidence Coefficient
Confidence = 90
 
# delay time between each interval
delaytime = 0.2
###############################
alpha2 = (100 - Confidence)/200
z = qnorm(1-alpha2)
xsd2 = xsd/sqrt(n)
L3 = mu-3*xsd2
H3 = mu+3*xsd2
xbarsd = 10/sqrt(n)
x = rnorm(nCI,mu,xsd)
 
plot(x,1:nCI,type="n",xlim=c(L3-3,H3+3),
xlab=expression(bar(X)),ylab="信賴區間產生順序")
abline(v=mu,col=3)
#abline(v=L3,lty=2)
#abline(v=H3,lty=2)
 
for (i in 1:nCI)
{
   x = rnorm(n,mu,xsd)
   ciL = mean(x) - z*(sd(x)/sqrt(n))
   ciH = mean(x) + z*(sd(x)/sqrt(n))
   if (mu < ciL || mu > ciH)
   {
     xcol=2
     lwd = 2
   }
   else
   {
     xcol=1
     lwd = 1
   }
   Sys.sleep(delaytime)
   lines(c(ciL,ciH),c(i,i),col=xcol,lwd=lwd)
}