months()、weekdays()、quarters(),通通上場!
作為日期主題的最後一課,這裡有幾個用來擷取日期組件的實用函式。其中一個是 months()。
my_date <- as.Date("2017-01-02")
months(my_date)
[1] "January"
另外兩個實用的函式是 weekdays(),用來擷取日期落在一週中的星期幾;以及 quarters(),用來判斷日期落在一年中的哪個季(Q1–Q4)。
本練習屬於課程
R 金融中級
練習說明
- 我們已為你建立了一個
dates向量。 - 從這些日期中擷取
months()。 - 從這些日期中擷取
quarters()。 - 另一個向量
dates2也已建立好。 - 使用
weekdays()判斷每個日期是星期幾,並用names()將結果指定為dates2的名稱。 - 印出
dates2。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# dates
dates <- as.Date(c("2017-01-02", "2017-05-03", "2017-08-04", "2017-10-17"))
# Extract the months
___
# Extract the quarters
___
# dates2
dates2 <- as.Date(c("2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05"))
# Assign the weekdays() of dates2 as the names()
___
# Print dates2
___