1

#read in data
dta <- read.table("C:/Users/user/Dropbox/1062-Data_manage/0409/inclass/hs0.txt", header=T)
#只看race是asian的資料
dta.asian <- subset(dta, race=="asian")
#看math與socst的相關係數
r0 <- cor(dta.asian$math, dta.asian$socst)
#設定參數
cnt <- 0
nIter <- 1001

解釋function

把read的順序重新排列,看他跟math的相關係數之間誰大誰小,如果重新排列後的read跟math的相關係數大於或等於math跟socst的相關係數,那就把cnt分數加一。最後跑1001次看總共有幾次是read跟math的相關係數比較大。

for (i in 1:nIter) {
  new <- sample(dta.asian$read)
  r <- cor(new, dta.asian$math)
  if ( r0 <= r ) cnt <- cnt+1
}

cnt/nIter
## [1] 0.03896104

試著把for拿掉

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.03596404

2

這個function可以顯示出每次隨機的x,y的散布圖,依照nIter設置的數量產生出多少張圖。 (不在html中真的印出512張圖)

Brownian <- function(n = 11, pause = 0.05, nIter = 2, ...) {
  x = rnorm(n)
  y = rnorm(n)
  i = 1
  while (i <= nIter) {
    plot(x, y, ...)
    text(x, y, cex = 0.5)
    x = x + rnorm(n)
    y = y + rnorm(n)
    Sys.sleep(pause)
    i = i + 1
  }
} 
### test it
Brownian(xlim = c(-20, 20), ylim = c(-20, 20), 
         pch = 21, cex = 2, col = "cyan", bg = "lavender") 

把while改成repeat

Brownian <- function(n = 11, pause = 0.05, nIter = 512, ...) {
  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
  }
} 

3

直接使用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       F 174.93
## 2       F 156.84
## 3       F 167.39
## 4       F 167.72
## 5       M 179.33
## 6       M 161.71
## 7       M 169.83
## 8       F 159.60
## 9       F 158.96
## 10      M 160.73