R语言21-R语法: 日期与时间

2019-05-03

R有一套特殊日期和时间的表示方法:

  • 日期使用 Date 类来表示
  • 时间是通过 POSIXct 或 POSIXlt 类来表示
  • R中储存的日期从1970-01-01这天开始的
  • R中储存的时间是从1970-01-01的第一秒开始的

日期

日期使用Date类来表示,可以使用 as.Date() 函数从字符串转换成日期。

> x <- as.Date("1970-01-01")
> x
[1] "1970-01-01"
> unclass(x)
[1] 0
> unclass(as.Date("1970-01-02"))
[1] 1

时间

时间使用 POSIXct 或 POSIXlt 类来表示。

  • POSIXct 实际是一个十分巨大的整数,当使用数据框来储存时间时十分方便。
  • POSIXlt 是一个列表,存储了年月周的哪一天等额外信息

有很多基本函数可以操作日期和时间

  • weekdays: 返回一周的第几天
  • months: 返回月份名称
  • quarters: 返回季度信息(“Q1”, “Q2”, “Q3”, or “Q4”)

通过 as.POSIXlt 或 as.POSIXct 函数将字符串转换为日期。

> x <- Sys.time()
> x
[1] "2019-05-08 21:24:57 CST"
> p <- as.POSIXlt(x)
> names(unclass(p))
 [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"  
 [9] "isdst"  "zone"   "gmtoff"
> p$sec
[1] 57.742

使用 POSIXct 格式表示日期。

# Sys.time()生成的时间默认为 ‘POSIXct’ 格式
> x 
[1] "2019-05-08 21:24:57 CST"
> unclass(x)
[1] 1557321898
> x$sec
Error in x$sec : $ operator is invalid for atomic vectors
> p <- as.POSIXlt(x)
> p$sec
[1] 57.742

使用 strptime 函数改变日期的格式。

> datestring <- c("May 8, 2019 10:30", "May 9, 2019 09:10")
> x <- strptime(datestring, "%B %d, %Y %H:%M")
> x
[1] "2019-05-08 10:30:00 CST" "2019-05-09 09:10:00 CST"
> class(x)
[1] "POSIXlt" "POSIXt" 
# 查看更多时间格式的帮助文档
> ?strptime

日期和时间的操作

日期和时间也可以用于数学计算(如+, -),也可以做比较 (如 ==, <=)。

> x <- as.Date("2020-05-08")
> y <- strptime("8 May 2019 10:34:21", "%d %b %Y %H:%M:%S") 
> x-y
Error in x - y : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("-.Date", "-.POSIXt") for "-" 
> x <- as.POSIXlt(x) 
> x-y
Time difference of 365.8928 days

也可以计算甚至可以跟踪闰年、闰秒、夏令时和时区。

> x <- as.Date("2019-03-01") 
> y <- as.Date("2019-02-28") 
> x-y
Time difference of 1 days
> x <- as.POSIXct("2019-05-08 01:00:00")
> y <- as.POSIXct("2019-05-08 06:00:00", tz = "GMT") 
> y-x
Time difference of 13 hours

小结

  • 日期和时间是R中特殊的类,允许数值和统计计算
  • 日期使用 Date 类
  • 时间使用 POSIXct 和 POSIXlt 类
  • 可以使用 strptime, as.Dateas.POSIXlt,  as.POSIXct 函数将字符串转换为日期/时间类