EX1:example for this problem,then eliminate the for loop in the code segment
dta <- read.table("hs0.txt", h=T)#讀入資料
dta.asian <- subset(dta, race=="asian")#把亞洲人之資料提取
r0 <- cor(dta.asian$math, dta.asian$socst)#取相關
cnt <- 0
i<-1
nIter <-1001 #重復做1001次
repeat{
new <- sample(dta.asian$read)
r <- cor(new, dta.asian$math)
i=i+1
if ( r0 <= r ) cnt <- cnt+1
if (i>=nIter)
break
}
cnt/nIter
## [1] 0.03596404
輸出的結果,感覺有點像老師今天講的用電腦取P值
EX2:example What does the R script do and Replace the “while” loop in the code.
顯示出每次隨機的x,y的散布圖
Brownian <- function(n = 11, pause = 0.05, nIter = 1, ...) {
x = rnorm(n)
y = rnorm(n)
i = 1
repeat {
plot(x, y, ...)
text(x, y, cex = 0.5)
x = x + rnorm(n)
y = y + rnorm(n)
Sys.sleep(pause)
i = i + 1
if(i >= nIter) break
}
}
Brownian(xlim = c(-20, 20), ylim = c(-20, 20),
pch = 21, cex = 2, col = "cyan", bg = "lavender")

EX3:矩陣調整
library("magrittr")
newsim<- function(n){
m <- matrix(nrow=n, ncol=2)
m[, 1] <- runif(n)
m[, 2] <- rnorm(n)
Gender <- ifelse(m[, 1]<0.505, "Male", "Female")
Height <- ifelse(m[, 1]<0.505, 170 + 7*m[, 2],160 + 5*m[, 2]) %>% round(2)
Person <- data.frame(Gender,Height)
return(Person)
}
newsim(10)
## Gender Height
## 1 Female 165.20
## 2 Female 154.27
## 3 Male 165.14
## 4 Female 161.62
## 5 Female 157.48
## 6 Male 169.50
## 7 Female 158.68
## 8 Female 149.99
## 9 Male 173.24
## 10 Male 176.26