fork download
  1. # 已知 x 和 g.date 是相互對應的二個向量
  2. x <- 1:365
  3. g.date <- seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day")
  4.  
  5. # 先對 x 和 g.date 重新排序(仍保留對應關係),後面會比較方便,也比較保險
  6. x <- x[order(g.date)]
  7. g.date <- g.date[order(g.date)]
  8.  
  9. # 取得月份
  10. g.month <- strftime(g.date, format = "%Y-%m")
  11.  
  12. # 用 for loop 得到和 tapply(x, g.month, mean) 一樣的結果
  13.  
  14. # 辦法是一個一個 x 元素加總到 res.sum 裡
  15. res.sum <- vector("numeric", length(table(g.month)))
  16. names(res.sum) <- names(table(g.month))
  17. res.N <- table(g.month)
  18. for (i in 1:length(x)) {
  19. var.month <- g.month[i]
  20. var.month.th <- which(var.month == names(res.sum))
  21. res.sum[var.month.th] <- x[i] + res.sum[var.month.th]
  22. }
  23.  
  24. res.sum / res.N # 為所求
  25.  
  26. # > res.sum / res.N # 為所求
  27. # g.month
  28. # 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12
  29. # 16.0 45.5 75.0 105.5 136.0 166.5 197.0 228.0 258.5 289.0 319.5 350.0
  30.  
  31. # > tapply(x, g.month, mean)
  32. # 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12
  33. # 16.0 45.5 75.0 105.5 136.0 166.5 197.0 228.0 258.5 289.0 319.5 350.0
  34.  
Success #stdin #stdout 0.19s 184064KB
stdin
Standard input is empty
stdout
g.month
2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 2018-08 2018-09 2018-10 
   16.0    45.5    75.0   105.5   136.0   166.5   197.0   228.0   258.5   289.0 
2018-11 2018-12 
  319.5   350.0