Question1

#設定路徑
setwd("/Users/tayloryen/Desktop/大學/成大課業/大四下/資料管理/0416")
#讀取資料
dta<-read.table("sch_dta.txt",header=T)
#查看資料前六比
head(dta)
##    id female  race    ses schtyp     prog read write math science socst
## 1  70   male white    low public  general   57    52   41      47    57
## 2 121 female white middle public vocation   68    59   53      63    61
## 3  86   male white   high public  general   44    33   54      58    31
## 4 141   male white   high public vocation   63    44   47      53    56
## 5 172   male white middle public academic   47    52   57      53    61
## 6 113   male white middle public academic   44    52   51      63    61
#查看資料格式
str(dta)
## 'data.frame':    200 obs. of  11 variables:
##  $ id     : int  70 121 86 141 172 113 50 11 84 48 ...
##  $ female : Factor w/ 2 levels "female","male": 2 1 2 2 2 2 2 2 2 2 ...
##  $ race   : Factor w/ 4 levels "african-amer",..: 4 4 4 4 4 4 1 3 4 1 ...
##  $ ses    : Factor w/ 3 levels "high","low","middle": 2 3 1 1 3 3 3 3 3 3 ...
##  $ schtyp : Factor w/ 2 levels "private","public": 2 2 2 2 2 2 2 2 2 2 ...
##  $ prog   : Factor w/ 3 levels "academic","general",..: 2 3 2 3 1 1 2 1 2 1 ...
##  $ read   : int  57 68 44 63 47 44 50 34 63 57 ...
##  $ write  : int  52 59 33 44 52 52 59 46 57 55 ...
##  $ math   : int  41 53 54 47 57 51 42 45 54 52 ...
##  $ science: int  47 63 58 53 53 63 53 39 58 NA ...
##  $ socst  : int  57 61 31 56 61 61 61 36 51 51 ...
#相關係數運算,並將for loop移除
dta.asian <- subset(dta, race=="asian")#只看race為asian的資料
r0 <- cor(dta.asian$math, dta.asian$socst)#Math和Socst相關係數
i=1
cnt=0
nIter <- 1001
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.04695305

Question2

##布朗運動模擬Function
Brownian <- function(n = 11, pause = 0.05, nIter = 3, ...) {
    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") 

Question3

newHeight <- function(n){
  set.seed(888)
  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       M 161.9873
## 2       M 178.2685
## 3       M 168.6597
## 4       F 163.1531
## 5       F 165.5179
## 6       M 169.6370
## 7       M 168.0411
## 8       M 164.7580
## 9       M 175.4402
## 10      F 157.4972