1
dta1 <- read.table("/Users/Hsin/Documents/hs0.txt", header = TRUE)
dta1.asian <- subset(dta1, race=="asian")
r0 <- cor(dta1.asian$math, dta1.asian$socst)
cnt <- 0
nIter <- 1001
i=1
cnt=0
repeat{
new <- sample(dta1.asian$read)
r <- cor(new, dta1.asian$math)
i=i+1
if ( r0 <= r ) cnt <- cnt+1
if (i>=nIter)
break
}
cnt/nIter
## [1] 0.03496503
2
#生成散布圖,依照niter限制的量出現相應數量的圖
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")

3
library(tidyr)
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 171.10
## 2 F 155.47
## 3 F 165.54
## 4 M 174.20
## 5 M 176.96
## 6 F 159.11
## 7 M 175.57
## 8 M 157.79
## 9 F 165.91
## 10 M 163.77