Q1

外面的lapply使用search列出目前所有物件,輸出成list 裡面的lapply使用length總結出物件的數量,輸出成list 最後計算所有search到的物件數量

Q2 L (r/(1-(1+r)^(-M))

f <- function(year){
  m <- 12*year
  l <- c(5000000, 10000000, 15000000)
  r <- c(0.02, 0.05, 0.07)
  p <- outer(l, r/(1-(outer((1+r), (-m), "^"))), "*")
  return(p)
}

mapply(f, year = c(10, 15, 20, 25, 30))
##            [,1]      [,2]      [,3]      [,4]      [,5]
##  [1,]  110240.5  102913.7  100870.4  100263.7  100080.2
##  [2,]  220481.0  205827.4  201740.8  200527.4  200160.4
##  [3,]  330721.5  308741.0  302611.2  300791.1  300240.7
##  [4,]  250718.6  250038.4  250002.1  250000.1  250000.0
##  [5,]  501437.1  500076.7  500004.1  500000.2  500000.0
##  [6,]  752155.7  750115.1  750006.2  750000.3  750000.0
##  [7,]  350104.3  350001.8  350000.0  350000.0  350000.0
##  [8,]  700208.5  700003.6  700000.1  700000.0  700000.0
##  [9,] 1050312.8 1050005.4 1050000.1 1050000.0 1050000.0

Q3-A

dta<-read.table("/Users/weisiang/Documents/DataManagement/school.txt",header = T)
outer(7:11, 7:11, 
  Vectorize(
    function (i,j) t.test(dta[,i], dta[,j])$p.value
  ) 
)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 1.0000000 0.5812665 0.6728327 0.7572410 0.8676815
## [2,] 0.5812665 1.0000000 0.8903494 0.3775863 0.7150322
## [3,] 0.6728327 0.8903494 1.0000000 0.4515844 0.8118467
## [4,] 0.7572410 0.3775863 0.4515844 1.0000000 0.6377587
## [5,] 0.8676815 0.7150322 0.8118467 0.6377587 1.0000000

Q3-B

library(ggplot2)
library(tidyr)
dta %>%
  gather(subject, score, 7:11) %>% 
  ggplot(., aes(race, score, color = subject, group = subject))+
  stat_summary(fun.data = mean_se,
               position = position_dodge(.5),
               na.rm = TRUE)+
  theme(legend.position = c(.8, .1), legend.direction = "horizontal")+
  theme_bw()

m <- manova(cbind(read, write, math, science, socst) ~ race - 1, data = dta)
summary(m, test = "Wilks")
##            Df    Wilks approx F num Df den Df    Pr(>F)    
## race        4 0.017354   74.385     20 621.16 < 2.2e-16 ***
## Residuals 191                                              
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Q3-C

lm(math ~ -1 + ses, data = dta)
## 
## Call:
## lm(formula = math ~ -1 + ses, data = dta)
## 
## Coefficients:
##   seshigh     seslow  sesmiddle  
##     56.17      49.17      52.21
ggplot(dta, aes(ses, math))+
  stat_summary(fun.data = mean_cl_boot, na.rm = TRUE)+
  scale_x_discrete(limits = c("low", "middle", "high"))+
  scale_y_continuous(breaks = seq(40, 70, by = 2.5))+
  labs(x = "SES", y = "Average Math Score")

Q4

     fcube <- function(x) { (1-x^2) }
     N <- 10000; x <- runif(N, 0, 1); y <- runif(N, 0, 1)
     curve(fcube, 0, 1, ylim = c(0, 1), ylab = "f(x)")
     points(x, y, col = ifelse(fcube(x) > y, 2, 3), pch = '.')

     integrate(fcube, 0, 1)
## 0.6666667 with absolute error < 7.4e-15