pacman::p_load(ggplot2, tidyverse, Hmisc)

##1

## lapply(lapply(search(), ls), length)

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

##2 P = 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))

##3 a

dta <- read.table("hs0.txt", header = TRUE)
outer(7:11, 7:11, 
  Vectorize(
    function (i,j) t.test(dta[,i], dta[,j])$p.value
  ) 
)

b

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")

c

lm(math ~ -1 + ses, data = dta)
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")

##4

fcube <- function(x) { (1+x)*(1-x) }
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)