R 的時間資料類別

在 R 中操作時間序列資料

Harrison Brown

Graduate Researcher in Geography

日期時間類別

  • numeric

    • 整數、浮點數等
    • August 9, 2022 = 19223
    • 自 1970 年 1 月 1 日起的天數
  • character

    • 文字字串、名稱等
    • August 9, 2022 = "2022-08-09"
    • August 9, 2022 = "August 9, 2022"
在 R 中操作時間序列資料

日期時間類別

  • Date
    • 日期、年內的天數
    • August 9, 2022 = "2022-08-09"
start_date <- as_date("2022-08-01")
end_date <- as_date("2022-08-09")

end_date - start_date
Time difference of 8 days
  • POSIXct
    • 日期「與」時間,含時區
    • August 9, 2022, 4:17 p.m. =
      • "2022-08-09 20:17:00 UTC"
start_time <-
  as.POSIXct("2022-08-01 08:57:00 EDT")
end_time <-
  as.POSIXct("2022-08-09 15:30:00 EDT")
end_time - start_time
Time difference of 8.272917 days
在 R 中操作時間序列資料

Lubridate

lubridate::as_date()

my_date <- as_date("2022-01-20")

my_date
[1] "2022-01-20"
class(my_date)
[1] "Date"

as_date()base::as.Date() 比較

  • 更佳的時區支援
  • 無效日期格式會警告
  • numeric 轉換更容易
  • ...
在 R 中操作時間序列資料

測試資料類別

class("2022-08-01")
[1] "character"
is.numeric(10494)
[1] TRUE
is.character("April 01, 2003")
[1] TRUE
is.Date(lubridate::today())
[1] TRUE
is.POSIXct(lubridate::now())
[1] TRUE
在 R 中操作時間序列資料

一起來練習吧!

在 R 中操作時間序列資料

Preparing Video For Download...