fork download
  1. # your code goes here# 已知 x 和 g.date 是相互對應的二個向量
  2. x <- 1:365
  3. g.date <-
  4. seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day")
  5.  
  6. # 先對 x 和 g.date 重新排序(仍保留對應關係),後面會比較方便,也比較保險
  7. x <- x[order(g.date)]
  8. g.date <- g.date[order(g.date)]
  9.  
  10. # 取得月份
  11. g.month <- strftime(g.date, format = "%Y-%m")
  12.  
  13. # 結果的容器
  14. res <- vector("numeric", length(unique(g.month)))
  15. names(res) <- unique(g.month)
  16.  
  17. # 用 2 層 for loop 得到和 tapply(x, g.month, mean) 一樣的結果
  18. # 猜測與模仿 AndrewShi@ptt.cc 的想法
  19. # https://w...content-available-to-author-only...t.cc/bbs/R_Language/M.1542102427.A.E65.html
  20. for (j in unique(g.month)) {
  21. # j 走訪每個月份,共12圈
  22. var.Sum <- 0
  23. var.N <- 0L
  24.  
  25. for (i in 1:length(g.date)) {
  26. # i 走訪每日,共365圈
  27.  
  28. if (strftime(g.date[i], format = "%Y-%m") == j) {
  29. # 若本日與 j 同,則累計總和與個數
  30. var.Sum <- var.Sum + x[i]
  31. var.N <- var.N + 1L
  32. }
  33.  
  34. }
  35.  
  36. # 一個 j 結算一次平均
  37. res[which(names(res) == j)] <- var.Sum / var.N
  38. }
  39.  
  40. print(res)
  41. print(tapply(x, g.month, mean))
  42.  
Success #stdin #stdout 0.3s 186432KB
stdin
Standard input is empty
stdout
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 
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