ex1

dta <- read.table("C:/Users/she22_000/Documents/hs0.txt", header = TRUE)
dta.asian <- subset(dta, race=="asian")
r0 <- cor(dta.asian$math, dta.asian$socst)
cnt <- 0
nIter <- 1001
i=1
cnt=0
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.03996004

ex2

## 利用repeat、if、break取代while
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") 

ex3

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       F 161.19
## 2       F 156.28
## 3       M 175.73
## 4       M 168.60
## 5       M 164.49
## 6       F 164.05
## 7       M 174.16
## 8       F 148.20
## 9       M 169.94
## 10      M 171.98