实际上,正如上面提到的(以及 SO 的其他地方),为了将字符串转换为日期,您需要一个特定的月份日期。从as.Date()
手册页:
如果日期字符串未完全指定日期,则返回的答案可能是系统特定的。最常见的行为是假设缺少的年、月或日是当前的。如果它错误地指定了一个日期,可靠的实现将给出一个错误并且日期报告为 NA。不幸的是,一些常见的实现(例如glibc
)是不可靠的并且猜测预期的含义。
一个简单的解决方案是将日期粘贴"01"
到每个日期并使用strptime()
将其指示为该月的第一天。
对于那些在 R 中寻求处理日期和时间的更多背景知识的人:
在 R 中,时间使用POSIXct
,POSIXlt
类和日期使用Date
类。
日期存储为自 1970 年 1 月 1 日以来的天数,时间存储为自 1970 年 1 月 1 日以来的秒数。
因此,例如:
d <- as.Date("1971-01-01")
unclass(d) # one year after 1970-01-01
# [1] 365
pct <- Sys.time() # in POSIXct
unclass(pct) # number of seconds since 1970-01-01
# [1] 1450276559
plt <- as.POSIXlt(pct)
up <- unclass(plt) # up is now a list containing the components of time
names(up)
# [1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday" "isdst" "zone"
# [11] "gmtoff"
up$hour
# [1] 9
要对日期和时间执行操作:
plt - as.POSIXlt(d)
# Time difference of 16420.61 days
要处理日期,您可以使用strptime()
(从手册页借用这些示例):
strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
# [1] "2006-02-20 11:16:16 EST"
# And in vectorized form:
dates <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
strptime(dates, "%d%b%Y")
# [1] "1960-01-01 EST" "1960-01-02 EST" "1960-03-31 EST" "1960-07-30 EDT"