Q1
dta <- read.table("hs0.txt", h = T)
dta.asian <- subset(dta, race=="asian") #只抽亞洲人
r0 <- cor(dta.asian$math, dta.asian$socst)
nIter <- 1001
#使用function
cnt <- function(nIter = 1001){
new <- replicate(nIter, sample(dta.asian$read))
r <- cor(new, dta.asian$math)
sum( r0 <= r )
}
cnt()/nIter
[1] 0.04195804
#使用while
i = 1
cnt = 0
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.04195804
Q2
#做布朗運動,隨機抽樣x,y,下一個運動點累加。
Brownian <- function(n = 11, pause = 0.05, nIter = 2, ...) {
x = rnorm(n)
y = rnorm(n)
for (i in 1:nIter) {
plot(x, y, ...)
text(x, y, cex = 0.5)
x = x + rnorm(n)
y = y + rnorm(n)
Sys.sleep(pause)
}
}
## test it
Brownian(xlim = c(-20, 20), ylim = c(-20, 20),
pch = 21, cex = 2, col = "cyan", bg = "lavender")


###
Q3
# draw n
newHeight <- function(n){
set.seed(7)
gender <- sample(c("M", "F"), n, replace = T, prob = c(0.505,0.495))
height <- ifelse(gender == "F",
rnorm(n, 160,5),
rnorm(n, 170,7))
data.frame(gender, height)
}
newHeight(10)
gender height
1 F 155.2636
2 M 163.7434
3 M 167.8487
4 M 169.9662
5 M 176.9171
6 F 161.7849
7 M 174.9374
8 F 171.4073
9 M 160.2840
10 M 178.9104