Ex2

library(magrittr)
cal_median_new <- function(x){
  newx <- x %>% sort()
  n <- length(x)
  if(n/2==0)
    (newx[n/2]+newx[n/2+1])/2
  else
    newx[(n+1)/2]
}

cal_median_new(women$height)
## [1] 65

EX3

riffle <- function(x, y) {
  dl <- length(x) - length(y)
  y[(length(y)+1):(length(y)+dl)] <- rep(NA, dl)
  c(na.omit(as.numeric(t(cbind(x,y)))))
}

# test it
riffle(1:10, 50:55)
##  [1]  1 50  2 51  3 52  4 53  5 54  6 55  7  8  9 10

##Ex 4

combo <- function(x){
  ll<-as.list(x)
  for(i in 2:length(x)){
    ll_new<-list(combn(x,i))
    ll<-c(ll,ll_new)
  }
  return(ll)
}
#text
x<-c("V1", "V2", "V3","V4")
combo(x)
## [[1]]
## [1] "V1"
## 
## [[2]]
## [1] "V2"
## 
## [[3]]
## [1] "V3"
## 
## [[4]]
## [1] "V4"
## 
## [[5]]
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] "V1" "V1" "V1" "V2" "V2" "V3"
## [2,] "V2" "V3" "V4" "V3" "V4" "V4"
## 
## [[6]]
##      [,1] [,2] [,3] [,4]
## [1,] "V1" "V1" "V1" "V2"
## [2,] "V2" "V2" "V3" "V3"
## [3,] "V3" "V4" "V4" "V4"
## 
## [[7]]
##      [,1]
## [1,] "V1"
## [2,] "V2"
## [3,] "V3"
## [4,] "V4"

Ex5

plot.new()

plot.window(xlim = c(0, 6), ylim = c(0, 6), asp = 1)

my_cl <- c("purple", "indianred", "orange", "yellow", "forestgreen", "dodgerblue",
           "violet")
for (i in 1:6) {
  for (j in 1:6) {
    kcol <- ((((i-1) * 6) + j) %% 7) + 1
    rect(j-1, i-1, j, i, col = my_cl[kcol])
  }
}

Ex6

set.seed(12345)

coin <- sample(c("H", "T"), 100, replace = TRUE)

coin.rle <- rle(coin)

plot(prop.table(table(coin.rle$lengths)), 
     xlab = "run length",
     ylab = "probability")

Ex7

#I still have no idea...