四捨五入實作練習
正如你在影片中看到的,round_date() 會把日期四捨五入到最近的單位,
floor_date() 會無條件捨去,
而 ceiling_date() 會無條件進位。
這三個函式都有一個 unit 參數,用來指定要四捨五入的粒度。你可以指定 "second"、"minute"、"hour"、"day"、"week"、"month"、"bimonth"、"quarter"、"halfyear" 或 "year"。也可以指定這些單位的倍數,例如 "5 years"、"3 minutes" 等等。
請用 R 3.4.1 的發佈時間來試試看。
本練習屬於課程
在 R 中處理日期與時間
練習說明
- 選擇正確的函式與單位,將
r_3_4_1捨去到當天(最接近的日)。 - 選擇正確的函式與單位,將
r_3_4_1四捨五入到最接近的 5 分鐘。 - 選擇正確的函式與單位,將
r_3_4_1進位到最近的一週。 - 將捨去到日的
r_3_4_1從r_3_4_1中相減,求出在發佈當天截至發佈時刻所經過的時間。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
r_3_4_1 <- ymd_hms("2016-05-03 07:13:28 UTC")
# Round down to day
___(r_3_4_1, unit = ___)
# Round to nearest 5 minutes
___(r_3_4_1, unit = ___)
# Round up to week
___(r_3_4_1, unit = ___)
# Subtract r_3_4_1 rounded down to day
r_3_4_1 - ___(r_3_4_1, unit = ___)