R 中的时间数据类型

R 中的时间序列数据处理

Harrison Brown

Graduate Researcher in Geography

日期时间类型

  • numeric

    • 整数、浮点数等
    • 2022 年 8 月 9 日 = 19223
    • 自 1970-01-01 起的天数
  • character

    • 文本字符串、名称等
    • 2022 年 8 月 9 日 = "2022-08-09"
    • 2022 年 8 月 9 日 = "August 9, 2022"
R 中的时间序列数据处理

日期时间类型

  • Date
    • 日期、年内的天数
    • 2022 年 8 月 9 日 = "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
    • 日期和时间,含时区
    • 2022 年 8 月 9 日 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 中的时间序列数据处理

Let's practice!

R 中的时间序列数据处理

Preparing Video For Download...