原for-loop
dta.asian <- subset(dta, race=="asian")
# 切割race="asian"
r0 <- cor(dta.asian$math, dta.asian$socst)
# math和socst的相關係數
cnt <- 0
nIter <- 1001
for (i in 1:nIter) # i依序帶入1~1001
{
new <- sample(dta.asian$read) # new=read的隨機抽樣
r <- cor(new, dta.asian$math) # r=new和math的相關
if ( r0 <= r ) cnt <- cnt+1 # 如果r0小於或等於r,cnt+1
}
cnt/nIter## [1] 0.03196803
使用eval = F,先不讓chunk輸出
newread <- replicate(nIter, sample(dta.asian$read))
# newread= 抽樣1001次read分數
newread <- data.frame(unlist(newread))
# newread轉換為資料框
with(newread, lapply(names(newread), function(x)
cor(dta.asian$math, eval(substitute(tmp, list(tmp=as.name(x))))))
)
# 計算相關係數的檢定
cor.test(dta[dta$race=="asian", "math"], dta[dta$race=="asian", "socst"])改while-loop
dta.asian <- subset(dta, race=="asian")
# 切割race="asian"
r0 <- cor(dta.asian$math, dta.asian$socst)
# math和socst的相關係數
cnt <- 0
nIter <- 1001
i <- 0
while (i <= nIter) # 當i小於1001時,依序帶入
{
i <- i+1
new <- sample(dta.asian$read) # new=read的隨機抽樣
r <- cor(new, dta.asian$math) # r=new和math的相關
if ( r0 <= r ) cnt <- cnt+1 # 如果r0小於或等於r,cnt+1
}
cnt/nIter## [1] 0.03596404
改repeat-loop
dta.asian <- subset(dta, race=="asian")
# 切割race="asian"
r0 <- cor(dta.asian$math, dta.asian$socst)
# math和socst的相關係數
cnt <- 0
nIter <- 1001
i <- 0
repeat # 重複執行,但當i大於1001時,則停止
{
if(i>nIter) break
i <- i+1
new <- sample(dta.asian$read) # new=read的隨機抽樣
r <- cor(new, dta.asian$math) # r=new和math的相關
if ( r0 <= r ) cnt <- cnt+1 # 如果r0小於或等於r,cnt+1
}
cnt/nIter## [1] 0.04895105