我在这里跟踪了几个问题, 询问如何将字符向量转换为日期类。 我经常看到两种方法, 一种是吸附时间, 另一种是 as. POSIXct/ as. POSIXlt 方法。 我查看了这两个函数, 但不清楚区别是什么 。
strptime
function (x, format, tz = "")
{
y <- .Internal(strptime(as.character(x), format, tz))
names(y$year) <- names(x)
y
}
<bytecode: 0x045fcea8>
<environment: namespace:base>
as.POSIXct
function (x, tz = "", ...)
UseMethod("as.POSIXct")
<bytecode: 0x069efeb8>
<environment: namespace:base>
as.POSIXlt
function (x, tz = "", ...)
UseMethod("as.POSIXlt")
<bytecode: 0x03ac029c>
<environment: namespace:base>
做一个微观基准,以确定是否存在性能差异:
library(microbenchmark)
Dates <- sample(c(dates = format(seq(ISOdate(2010,1,1), by= day , length=365), format= %d-%m-%Y )), 5000, replace = TRUE)
df <- microbenchmark(strptime(Dates, "%d-%m-%Y"), as.POSIXlt(Dates, format = "%d-%m-%Y"), times = 1000)
Unit: milliseconds
expr min lq median uq max
1 as.POSIXlt(Dates, format = "%d-%m-%Y") 32.38596 33.81324 34.78487 35.52183 61.80171
2 strptime(Dates, "%d-%m-%Y") 31.73224 33.22964 34.20407 34.88167 52.12422
运动时间似乎稍快一些。那又有什么意义呢?为什么有两种相似的功能,或者我错过了两种功能之间的差异呢?