EX01
dta <- read.table("hs0.txt", header=T)
dta.asian <- subset(dta, race=="asian") #只挑亞洲學生
r0 <- cor(dta.asian$math, dta.asian$socst) #亞洲學生math和scost的相關r0
nIter <- 1001 #設定參數
i=1
cnt=0
repeat{
new <- sample(dta.asian$read) #隨機排序read
r1 <- cor(new, dta.asian$math) #新排序後的read和math的相關r1
i=i+1
if ( r0 <= r1 ) cnt <- cnt+1 #累計r0 <= r1的次數
if (i >= nIter) break
}
cnt/nIter
## [1] 0.03496503
EX02
#透過function顯示以nlter設置次數的隨機的x,y之plot(原設定為512,以下設定3示意)
Brownian <- function(n = 5, pause = 0.05, nIter = 3, ...) {
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")



EX03
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 Male 171.05
## 2 Male 172.98
## 3 Male 164.73
## 4 Male 161.88
## 5 Male 164.94
## 6 Female 157.21
## 7 Male 169.37
## 8 Female 167.34
## 9 Female 157.39
## 10 Male 161.43