## EX1

# 讀取檔案，並只觀察種族為亞洲人的資料，透過math與socst的相關係數確立r0
dta.asian <- subset(dta, race=="asian")
r0 <- cor(dta.asian$math, dta.asian$socst)
# 重複1001次後有多少相關係數比原本的高
cnt <- 0
nIter <- 1001
i = 1
# 用while跟if取代原本的for
while(i <= nIter){
new <- sample(dta.asian$read) r <- cor(new,dta.asian$math)
if(r0 <= r) cnt <- cnt+1
i = i+1
}
cnt/nIter
## [1] 0.03696304
#

## EX2

# 透過function顯示以nlter設置的隨機的x,y之plot
# 透過repeat跟if,break取代while
Brownian <- function(n = 5, 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

# 嘗試用ifelse調整亂數部分的m矩陣
newsim<- function(n){
m <- matrix(nrow=n, ncol=2)
m[, 1] <- runif(n)
m[, 2] <- rnorm(n)
Gender <- ifelse(m[, 1]<0.5, "M", "F")
Height <- ifelse(m[, 1]<0.5, 170 + 7*m[, 2],160 + 5*m[, 2]) %>% round(2)
Person <- data.frame(Gender,Height)
return(Person)
}

newsim(10)
##    Gender Height
## 1       M 157.88
## 2       F 159.59
## 3       F 169.14
## 4       M 168.19
## 5       F 155.64
## 6       F 156.11
## 7       M 172.53
## 8       M 155.87
## 9       M 162.30
## 10      F 156.13
###