---
# System prepended metadata

title: 迴圈練習：*T* 檢定與樣本數預測
tags: [R教學, 基礎教學]

---

# 迴圈練習：*T* 檢定與樣本數預測
###### tags: `R教學` `基礎教學`

```r=
rm(list=ls())
##### p-value  #####
n <- c(seq(2,30,1), 40, 60, 80, 100)
rep <- 30

pT.valus <- NULL
pN.valus <- NULL

for (k in 1:rep){
  pT <- rep(NA, length(n))
  pN <- rep(NA, length(n))
  for (j in 1:length(n)){
    s.t <- numeric(1000)
    for( i in 1:1000 ){
      s.m <- rnorm(n[j],5,2)
      s.t[i] <- (mean(s.m)-5)/(sd(s.m)/sqrt(n[j]))
    }
    pT [j] <- length(s.t[s.t<qt(0.025, n[j]-1) | s.t>qt(0.975, n[j]-1)])/1000
    pN [j] <- length(s.t[s.t<qnorm(0.025, 0, 1) | s.t>qnorm(0.975, 0, 1)])/1000
  }
  pT.valus <- cbind (pT.valus, pT)
  pN.valus <- cbind (pN.valus, pN)
}

rownames(pT.valus) <- n
rownames(pN.valus) <- n

place <- c(seq(2,30,1), 33, 35, 37, 39)
plot(place, apply(pT.valus, 1, mean), ylim = c(0,0.4), pch = 19, xaxt = "n",
     xlab = "樣本數", ylab = "P-value", las = 1)
abline (h = 0.05, lty = 3)
arrows(place,apply(pT.valus, 1, mean) + apply(pT.valus, 1, sd),
       place,apply(pT.valus, 1, mean) - apply(pT.valus, 1, sd),
       code=3,length=0.05,angle=90,lty=3, col=1)
axis (1, at = place, labels = n)
axis (2, at = 0.05, labels = 0.05, las = 1)
text (5, 0.08, "T-distribution")

points(place, apply(pN.valus, 1, mean), ylim = c(0,0.3), pch = 19, col = 2)
arrows(place,apply(pN.valus, 1, mean) + apply(pN.valus, 1, sd),
       place,apply(pN.valus, 1, mean) - apply(pN.valus, 1, sd),
       code=3,length=0.05,angle=90,lty=3, col=2)
text (10, 0.15, "Normal-distribution", col =2)


#boxplot(t(pT.valus), at = place, ylim = c(0,0.4))
#boxplot(t(pN.valus), at = place, ylim = c(0,0.4), add = T, col = 2)
#abline (h = 0.05, lty = 3)
```
