# your code goes here# 已知 x 和 g.date 是相互對應的二個向量
x <- 1:365
g.date <-
  seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day")

# 先對 x 和 g.date 重新排序（仍保留對應關係），後面會比較方便，也比較保險
x <- x[order(g.date)]
g.date <- g.date[order(g.date)]

# 取得月份
g.month <- strftime(g.date, format = "%Y-%m")

# 結果的容器
res <- vector("numeric", length(unique(g.month)))
names(res) <- unique(g.month)

# 用 2 層 for loop 得到和 tapply(x, g.month, mean) 一樣的結果
# 猜測與模仿 AndrewShi@ptt.cc 的想法
# https://w...content-available-to-author-only...t.cc/bbs/R_Language/M.1542102427.A.E65.html
for (j in unique(g.month)) {
  # j 走訪每個月份，共12圈
  var.Sum <- 0
  var.N <- 0L

  for (i in 1:length(g.date)) {
    # i 走訪每日，共365圈
  
    if (strftime(g.date[i], format = "%Y-%m") == j) {
      # 若本日與 j 同，則累計總和與個數
      var.Sum <- var.Sum + x[i]
      var.N <- var.N + 1L
    }
    
  }

  # 一個 j 結算一次平均
  res[which(names(res) == j)] <- var.Sum / var.N
}

print(res)
print(tapply(x, g.month, mean))
