# 已知 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")

# 用 for loop 得到和 tapply(x, g.month, mean) 一樣的結果

# 辦法是一個一個 x 元素加總到 res.sum 裡
res.sum <- vector("numeric", length(table(g.month)))
names(res.sum) <- names(table(g.month))
res.N <- table(g.month)
for (i in 1:length(x)) {
  var.month <- g.month[i]
  var.month.th <- which(var.month == names(res.sum))
  res.sum[var.month.th] <- x[i] + res.sum[var.month.th]
}

res.sum / res.N # 為所求

# > res.sum / res.N # 為所求
# g.month
# 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 
#    16.0    45.5    75.0   105.5   136.0   166.5   197.0   228.0   258.5   289.0   319.5   350.0 

# > tapply(x, g.month, mean)
# 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 
#    16.0    45.5    75.0   105.5   136.0   166.5   197.0   228.0   258.5   289.0   319.5   350.0 
