日期的減法
就像數值一樣,日期也可以做運算。特別是,你可以用減法求出兩個日期之間相差的天數:
today <- as.Date("2017-01-02")
tomorrow <- as.Date("2017-01-03")
one_year_away <- as.Date("2018-01-02")
tomorrow - today
Time difference of 1 days
one_year_away - today
Time difference of 365 days
你也可以改用 difftime() 函式來取得時間差。
difftime(tomorrow, today)
Time difference of 1 days
# 還可以搭配額外選項!
difftime(tomorrow, today, units = "secs")
Time difference of 86400 secs
本練習屬於課程
R 金融中級
練習說明
- 我們已經為你建立了一個
dates向量。 - 你可以用相減來驗證 1970 年 1 月 1 日是 R 起算的第一天。先建立一個名為
origin的變數,內容是作為日期的"1970-01-01"。 - 接著,對
dates使用as.numeric(),看看距離 1970 年 1 月 1 日已經過了多少天。 - 最後,用
dates減去origin來驗證結果!(注意這裡用了回收機制!)
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Dates
dates <- as.Date(c("2017-01-01", "2017-01-02", "2017-01-03"))
# Create the origin
origin <- ___
# Use as.numeric() on dates
___
# Find the difference between dates and origin
___